<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🤖 ShuYixiao Agent - RAG 智能助手</title>
    
    <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><defs><linearGradient id='grad' x1='0%25' y1='0%25' x2='100%25' y2='100%25'><stop offset='0%25' style='stop-color:%23667eea;stop-opacity:1' /><stop offset='100%25' style='stop-color:%23764ba2;stop-opacity:1' /></linearGradient></defs><rect width='100' height='100' rx='20' fill='url(%23grad)'/><circle cx='35' cy='40' r='8' fill='white'/><circle cx='65' cy='40' r='8' fill='white'/><path d='M 30 65 Q 50 75 70 65' stroke='white' stroke-width='6' fill='none' stroke-linecap='round'/></svg>">
    
    <script src="https://cdn.jsdelivr.net/npm/marked@11.1.1/marked.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.8/dist/purify.min.js"></script>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            overflow: hidden;
            display: flex;
            flex-direction: column;
            height: calc(100vh - 40px);
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 24px;
            font-weight: 600;
        }

        .status-badge {
            background: rgba(255, 255, 255, 0.2);
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .status-dot {
            width: 8px;
            height: 8px;
            background: #4ade80;
            border-radius: 50%;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        .tabs {
            display: flex;
            background: #f8f9fa;
            border-bottom: 2px solid #e9ecef;
        }

        .tab {
            padding: 15px 30px;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 15px;
            font-weight: 500;
            color: #6c757d;
            transition: all 0.3s;
            position: relative;
        }

        .tab:hover {
            color: #667eea;
            background: rgba(102, 126, 234, 0.05);
        }

        .tab.active {
            color: #667eea;
            background: white;
        }

        .tab.active::after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 0;
            right: 0;
            height: 2px;
            background: #667eea;
        }

        .content {
            flex: 1;
            display: flex;
            overflow: hidden;
        }

        .tab-content {
            display: none;
            flex: 1;
            flex-direction: column;
            overflow: hidden;
        }

        .tab-content.active {
            display: flex;
        }

        /* 聊天区域 */
        .chat-area {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;
        }

        .chat-controls {
            padding: 15px 20px;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .control-group {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .control-group label {
            font-size: 14px;
            color: #495057;
            font-weight: 500;
        }

        select, input[type="number"], input[type="text"] {
            padding: 8px 12px;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            font-size: 14px;
            background: white;
            transition: all 0.3s;
        }

        select:focus, input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .btn-danger {
            background: #ef4444;
            color: white;
        }

        .btn-danger:hover {
            background: #dc2626;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .chat-container {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #f8f9fa;
        }

        .message {
            display: flex;
            margin-bottom: 16px;
            animation: slideIn 0.3s ease-out;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .message.user {
            justify-content: flex-end;
        }

        .message-content {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 12px;
            word-wrap: break-word;
            line-height: 1.5;
        }

        .message.user .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .message.assistant .message-content {
            background: white;
            color: #333;
            border: 1px solid #dee2e6;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .message-content code {
            background: rgba(0, 0, 0, 0.05);
            padding: 2px 6px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 0.9em;
        }

        .message-content pre {
            background: #2d2d2d;
            color: #f8f8f2;
            padding: 12px;
            border-radius: 8px;
            overflow-x: auto;
            margin: 8px 0;
        }

        .typing-indicator {
            display: inline-flex;
            gap: 4px;
        }

        .typing-indicator span {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: #667eea;
            animation: typing 1.4s infinite;
        }

        .typing-indicator span:nth-child(2) {
            animation-delay: 0.2s;
        }

        .typing-indicator span:nth-child(3) {
            animation-delay: 0.4s;
        }

        @keyframes typing {
            0%, 60%, 100% {
                opacity: 0.3;
                transform: translateY(0);
            }
            30% {
                opacity: 1;
                transform: translateY(-4px);
            }
        }

        .input-area {
            padding: 20px;
            background: white;
            border-top: 1px solid #e9ecef;
        }

        .input-container {
            display: flex;
            gap: 10px;
        }

        #userInput {
            flex: 1;
            padding: 12px 16px;
            border: 2px solid #dee2e6;
            border-radius: 10px;
            font-size: 14px;
            resize: none;
            font-family: inherit;
            max-height: 120px;
        }

        #sendBtn {
            padding: 12px 30px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        #sendBtn:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
        }

        .empty-state {
            text-align: center;
            color: #6c757d;
            padding: 60px 20px;
        }

        .empty-state svg {
            width: 80px;
            height: 80px;
            margin-bottom: 16px;
            opacity: 0.3;
        }

        /* RAG 区域 */
        .rag-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            padding: 20px;
            overflow-y: auto;
        }

        .rag-card {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 12px;
            padding: 20px;
            height: fit-content;
        }

        .rag-card h3 {
            font-size: 18px;
            margin-bottom: 16px;
            color: #495057;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .form-group {
            margin-bottom: 16px;
        }

        .form-group label {
            display: block;
            font-size: 14px;
            color: #495057;
            margin-bottom: 6px;
            font-weight: 500;
        }

        textarea {
            width: 100%;
            padding: 10px;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            font-size: 14px;
            font-family: inherit;
            resize: vertical;
            min-height: 100px;
        }

        .info-item {
            display: flex;
            justify-content: space-between;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 8px;
        }

        .info-label {
            font-weight: 500;
            color: #495057;
        }

        .info-value {
            color: #667eea;
            font-weight: 600;
        }

        .alert {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 16px;
            font-size: 14px;
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border: 1px solid #10b981;
        }

        .alert-error {
            background: #fee;
            color: #c33;
            border: 1px solid #ef4444;
        }

        .alert-info {
            background: #dbeafe;
            color: #1e40af;
            border: 1px solid #3b82f6;
        }

        .loading-spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top-color: white;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        @media (max-width: 1024px) {
            .rag-section {
                grid-template-columns: 1fr;
            }
        }

        .scrollbar::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        .scrollbar::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        .scrollbar::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }

        .scrollbar::-webkit-scrollbar-thumb:hover {
            background: #a1a1a1;
        }

        /* 文档浏览器样式 */
        .doc-browser {
            max-height: 400px;
            overflow-y: auto;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            margin-top: 12px;
        }

        .doc-item {
            padding: 12px;
            border-bottom: 1px solid #e9ecef;
            transition: background 0.2s;
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 10px;
        }

        .doc-item:hover {
            background: #f8f9fa;
        }

        .doc-checkbox {
            margin-right: 8px;
            cursor: pointer;
        }

        .doc-item:last-child {
            border-bottom: none;
        }

        .doc-content {
            flex: 1;
            min-width: 0;
        }

        .doc-id {
            font-size: 11px;
            color: #6c757d;
            font-family: 'Courier New', monospace;
            margin-bottom: 4px;
        }

        .doc-text {
            font-size: 13px;
            color: #495057;
            line-height: 1.4;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }

        .doc-actions {
            display: flex;
            gap: 6px;
            flex-shrink: 0;
        }

        .btn-sm {
            padding: 4px 10px;
            font-size: 12px;
            border-radius: 6px;
        }

        .btn-view {
            background: #667eea;
            color: white;
        }

        .btn-view:hover {
            background: #5568d3;
        }

        .btn-delete {
            background: #ef4444;
            color: white;
        }

        .btn-delete:hover {
            background: #dc2626;
        }

        .doc-stats {
            display: flex;
            gap: 12px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 12px;
            font-size: 13px;
        }

        .doc-stat-item {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .doc-stat-label {
            color: #6c757d;
        }

        .doc-stat-value {
            color: #667eea;
            font-weight: 600;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(4px);
        }

        .modal.active {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: white;
            border-radius: 12px;
            max-width: 600px;
            width: 90%;
            max-height: 80vh;
            display: flex;
            flex-direction: column;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        }

        .modal-header {
            padding: 20px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            margin: 0;
            font-size: 18px;
            color: #495057;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            color: #6c757d;
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 6px;
            transition: all 0.2s;
        }

        .modal-close:hover {
            background: #f8f9fa;
            color: #495057;
        }

        .modal-body {
            padding: 20px;
            overflow-y: auto;
            flex: 1;
        }

        .modal-body .doc-id {
            font-size: 12px;
            margin-bottom: 12px;
        }

        .modal-body .doc-text {
            font-size: 14px;
            line-height: 1.6;
            color: #333;
            white-space: pre-wrap;
            word-wrap: break-word;
            display: block;
            -webkit-line-clamp: unset;
        }

        .modal-footer {
            padding: 16px 20px;
            border-top: 1px solid #e9ecef;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 ShuYixiao Agent - RAG 智能助手</h1>
            <div class="status-badge">
                <div class="status-dot"></div>
                <span>在线</span>
            </div>
        </div>

        <div class="tabs">
            <button class="tab active" onclick="switchTab('chat')">💬 智能对话</button>
            <button class="tab" onclick="switchTab('rag')">📚 RAG 问答</button>
            <button class="tab" onclick="switchTab('knowledge')">🗄️ 知识库管理</button>
            <button class="tab" onclick="switchTab('prompting')">🔗 Prompt Chaining</button>
            <button class="tab" onclick="switchTab('routing')">🎯 Routing Agent</button>
            <button class="tab" onclick="switchTab('parallelization')">🚀 Parallelization Agent</button>
            <button class="tab" onclick="switchTab('reflection')">💭 Reflection Agent</button>
            <button class="tab" onclick="switchTab('tooluse')">🔧 Tool Use Agent</button>
            <button class="tab" onclick="switchTab('planning')">📋 Planning Agent</button>
            <button class="tab" onclick="switchTab('multiagent')">👥 Multi-Agent Collaboration</button>
            <button class="tab" onclick="switchTab('memory')">🧠 Memory Management</button>
        </div>

        <div class="content">
            <!-- 智能对话标签页 -->
            <div id="chatTab" class="tab-content active">
                <div class="chat-area">
                    <div class="chat-controls">
                        <div class="control-group">
                            <label>Agent 类型：</label>
                            <select id="agentType">
                                <option value="simple">简单对话</option>
                                <option value="tool">工具调用</option>
                            </select>
                        </div>
                        <button class="btn btn-danger" onclick="clearChatHistory()">清除历史</button>
                    </div>

                    <div class="chat-container scrollbar" id="chatContainer">
                        <div class="empty-state">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
                            </svg>
                            <h3>开始对话</h3>
                            <p>选择 Agent 类型，然后输入您的问题开始对话</p>
                        </div>
                    </div>

                    <div class="input-area">
                        <div class="input-container">
                            <textarea id="userInput" placeholder="输入您的问题..." rows="1"></textarea>
                            <button id="sendBtn" onclick="sendMessage()">发送</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- RAG 问答标签页 -->
            <div id="ragTab" class="tab-content">
                <div class="chat-area">
                    <div class="chat-controls">
                        <div class="control-group">
                            <label>知识库：</label>
                            <select id="ragCollection" style="min-width: 200px;">
                                <option value="">-- 请选择知识库 --</option>
                            </select>
                        </div>
                        <div class="control-group">
                            <label>检索模式：</label>
                            <select id="retrievalMode">
                                <option value="hybrid">混合检索</option>
                                <option value="vector">向量检索</option>
                                <option value="keyword">关键词检索</option>
                            </select>
                        </div>
                        <div class="control-group">
                            <label>Top K：</label>
                            <input type="number" id="topK" value="5" min="1" max="20" style="width: 70px;">
                        </div>
                        <div class="checkbox-group">
                            <input type="checkbox" id="optimizeQuery" checked>
                            <label for="optimizeQuery">查询优化</label>
                        </div>
                        <div class="checkbox-group">
                            <input type="checkbox" id="useHistory" checked>
                            <label for="useHistory">使用历史</label>
                        </div>
                        <button class="btn btn-danger" onclick="clearRagHistory()">清除历史</button>
                    </div>

                    <div class="chat-container scrollbar" id="ragChatContainer">
                        <div class="empty-state">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
                            </svg>
                            <h3>RAG 问答</h3>
                            <p>基于知识库的智能问答，支持多种检索模式</p>
                        </div>
                    </div>

                    <div class="input-area">
                        <div class="input-container">
                            <textarea id="ragInput" placeholder="输入您的问题..." rows="1"></textarea>
                            <button id="ragSendBtn" onclick="sendRagQuery()">发送</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 知识库管理标签页 -->
            <div id="knowledgeTab" class="tab-content">
                <div class="rag-section scrollbar">
                    <!-- 上传文本 -->
                    <div class="rag-card">
                        <h3>📝 上传文本</h3>
                        <div class="form-group">
                            <label>知识库名称：</label>
                            <input type="text" id="uploadCollection" value="default" placeholder="default">
                        </div>
                        <div class="form-group">
                            <label>文本内容（每行一个文档）：</label>
                            <textarea id="textContent" placeholder="输入要添加到知识库的文本..."></textarea>
                        </div>
                        <button class="btn btn-primary" onclick="uploadTexts()" style="width: 100%;">上传文本</button>
                        <div id="uploadTextResult"></div>
                    </div>

                    <!-- 知识库信息 -->
                    <div class="rag-card">
                        <h3>ℹ️ 知识库信息</h3>
                        <div class="form-group">
                            <label>查询知识库：</label>
                            <select id="infoCollection" style="width: 100%; padding: 10px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;">
                                <option value="">-- 请先加载知识库列表 --</option>
                            </select>
                        </div>
                        <button class="btn btn-secondary" onclick="getKnowledgeInfo()" style="width: 100%; margin-bottom: 16px;">刷新信息</button>
                        <div id="knowledgeInfo">
                            <div class="alert alert-info">点击"刷新信息"查看知识库状态</div>
                        </div>
                    </div>

                    <!-- 所有知识库列表 -->
                    <div class="rag-card">
                        <h3>📚 所有知识库</h3>
                        <p style="font-size: 13px; color: #6c757d; margin-bottom: 12px;">
                            显示data/chroma目录下的所有已存在知识库
                        </p>
                        <button class="btn btn-secondary" onclick="loadAllCollections()" style="width: 100%; margin-bottom: 16px;">刷新列表</button>
                        <div id="collectionsList"></div>
                    </div>

                    <!-- 名称映射表 -->
                    <div class="rag-card">
                        <h3>🔗 名称映射表</h3>
                        <p style="font-size: 13px; color: #6c757d; margin-bottom: 12px;">
                            显示原始知识库名称与系统内部编码名称的对应关系
                        </p>
                        <button class="btn btn-secondary" onclick="loadMappings()" style="width: 100%; margin-bottom: 16px;">加载映射关系</button>
                        <div id="mappingsList"></div>
                    </div>

                    <!-- 文件上传 -->
                    <div class="rag-card">
                        <h3>📁 上传文件</h3>
                        <div class="form-group">
                            <label>知识库名称：</label>
                            <input type="text" id="fileUploadCollection" value="default" placeholder="default">
                        </div>
                        <div class="form-group">
                            <label>文件路径（绝对路径）：</label>
                            <input type="text" id="filePath" placeholder="E:\docs\document.txt">
                        </div>
                        <button class="btn btn-primary" onclick="uploadFile()" style="width: 100%;">上传文件</button>
                        <div id="uploadFileResult"></div>
                    </div>

                    <!-- 知识库管理 -->
                    <div class="rag-card">
                        <h3>🗑️ 知识库管理</h3>
                        <div class="form-group">
                            <label>知识库名称：</label>
                            <input type="text" id="manageCollection" value="default" placeholder="default">
                        </div>
                        <button class="btn btn-danger" onclick="clearKnowledgeBase()" style="width: 100%; margin-bottom: 12px;">清空知识库</button>
                        <div class="alert alert-info" style="margin: 0;">
                            ⚠️ 清空知识库将删除所有文档，此操作不可恢复！
                        </div>
                    </div>

                    <!-- 文档浏览器 -->
                    <div class="rag-card" style="grid-column: 1 / -1;">
                        <h3>📄 文档浏览器</h3>
                        <div class="form-group">
                            <label>查看知识库：</label>
                            <select id="browserCollection" style="width: 100%; padding: 10px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;">
                                <option value="">-- 请先加载知识库列表 --</option>
                            </select>
                        </div>
                        <div style="display: flex; gap: 10px; margin-bottom: 12px;">
                            <button class="btn btn-secondary" onclick="loadDocuments()" style="flex: 1;">加载文档列表</button>
                            <button class="btn btn-secondary" onclick="refreshDocuments()">刷新</button>
                            <button class="btn btn-danger" onclick="batchDeleteDocuments()" id="batchDeleteBtn" style="display: none;">删除选中</button>
                        </div>
                        <div id="docStats"></div>
                        <div id="docBrowser"></div>
                    </div>
                </div>
            </div>

            <!-- Routing Agent 标签页 -->
            <div id="routingTab" class="tab-content">
                <div class="rag-section scrollbar">
                    <!-- 场景和策略选择 -->
                    <div class="rag-card" style="grid-column: 1 / -1;">
                        <h3>🎯 Routing Agent - 智能路由</h3>
                        <p style="font-size: 14px; color: #6c757d; margin-bottom: 20px;">
                            根据任务类型智能选择最合适的处理器，实现精准、高效的任务分发
                        </p>
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 20px;">
                            <div class="form-group" style="margin-bottom: 0;">
                                <label>选择场景：</label>
                                <select id="routingScenario" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;" onchange="loadRoutingRoutes()">
                                    <option value="">-- 加载中 --</option>
                                </select>
                            </div>
                            
                            <div class="form-group" style="margin-bottom: 0;">
                                <label>路由策略：</label>
                                <select id="routingStrategy" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;">
                                    <option value="hybrid">🔄 混合路由（推荐）</option>
                                    <option value="llm_based">🤖 LLM路由</option>
                                    <option value="keyword">🔍 关键词路由</option>
                                    <option value="rule_based">📏 规则路由</option>
                                </select>
                            </div>
                        </div>

                        <!-- 场景信息 -->
                        <div id="routingScenarioInfo" style="display: none; background: #f8f9fa; padding: 16px; border-radius: 8px; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #495057;">场景信息</h4>
                            <div id="routingDescription" style="margin-bottom: 12px; color: #6c757d;"></div>
                            <div id="routingRoutesList" style="margin-bottom: 12px;"></div>
                        </div>

                        <!-- 策略说明 -->
                        <div id="routingStrategyInfo" style="background: #e7f5ff; padding: 12px; border-radius: 8px; margin-bottom: 20px; font-size: 13px;">
                            <strong>💡 策略说明：</strong> <span id="strategyDescription">混合路由结合规则、关键词和LLM的优势，平衡效率和准确性</span>
                        </div>

                        <div class="form-group">
                            <label id="routingInputLabel">输入任务：</label>
                            <textarea id="routingInput" placeholder="例如：帮我写一个Python排序函数" rows="6" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px; font-family: inherit; resize: vertical;"></textarea>
                        </div>

                        <div style="display: flex; gap: 10px;">
                            <button class="btn btn-primary" onclick="executeRouting()" id="routingExecuteBtn" style="flex: 1;">
                                <span>🚀 执行路由</span>
                            </button>
                            <button class="btn btn-secondary" onclick="clearRoutingResult()">
                                🗑️ 清除结果
                            </button>
                        </div>
                    </div>

                    <!-- 路由结果展示 -->
                    <div class="rag-card" style="grid-column: 1 / -1; display: none;" id="routingResultCard">
                        <h3>📊 路由结果</h3>
                        
                        <!-- 路由决策 -->
                        <div id="routingDecision" style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #667eea;">
                            <h4 style="margin-bottom: 16px; color: #495057;">🔀 路由决策</h4>
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px;">
                                <div class="info-item">
                                    <span class="info-label">选择路由：</span>
                                    <span class="info-value" id="selectedRoute"></span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">置信度：</span>
                                    <span class="info-value" id="routingConfidence"></span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">执行时间：</span>
                                    <span class="info-value" id="routingTime"></span>
                                </div>
                            </div>
                            <div style="margin-top: 12px; padding: 10px; background: rgba(102, 126, 234, 0.1); border-radius: 6px;">
                                <strong style="font-size: 13px; color: #495057;">💡 路由原因：</strong>
                                <p id="routingReason" style="margin: 8px 0 0 0; font-size: 13px; color: #6c757d;"></p>
                            </div>
                        </div>

                        <!-- 置信度可视化 -->
                        <div style="margin-bottom: 20px;">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                                <span style="font-size: 14px; font-weight: 500; color: #495057;">匹配置信度</span>
                                <span id="confidencePercent" style="font-size: 14px; font-weight: 600; color: #667eea;">0%</span>
                            </div>
                            <div style="background: #e9ecef; height: 12px; border-radius: 6px; overflow: hidden;">
                                <div id="confidenceBar" style="background: linear-gradient(90deg, #667eea, #764ba2); height: 100%; width: 0%; transition: width 0.5s;"></div>
                            </div>
                        </div>

                        <!-- 处理结果 -->
                        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745;">
                            <h4 style="margin-bottom: 12px; color: #495057;">✨ 处理结果</h4>
                            <div id="routingOutput" class="markdown-content"></div>
                        </div>

                        <!-- 操作按钮 -->
                        <div style="display: flex; gap: 10px; margin-top: 16px;">
                            <button class="btn btn-secondary" onclick="copyRoutingResult()">
                                📋 复制结果
                            </button>
                        </div>
                    </div>

                    <!-- 可用路由列表 -->
                    <div class="rag-card" style="grid-column: 1 / -1;">
                        <h3>📋 可用路由</h3>
                        <p style="font-size: 13px; color: #6c757d; margin-bottom: 12px;">
                            当前场景下的所有可用路由和说明
                        </p>
                        <div id="availableRoutes"></div>
                    </div>
                </div>
            </div>

            <!-- Parallelization Agent 标签页 -->
            <div id="parallelizationTab" class="tab-content">
                <div class="rag-section scrollbar">
                    <!-- 场景选择 -->
                    <div class="rag-card" style="grid-column: 1 / -1;">
                        <h3>🚀 Parallelization Agent - 并行化智能体</h3>
                        <p style="font-size: 14px; color: #6c757d; margin-bottom: 20px;">
                            同时执行多个任务，通过并行处理提高效率、获得多角度视角，提升结果质量
                        </p>
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 16px; margin-bottom: 20px;">
                            <div class="form-group" style="margin-bottom: 0;">
                                <label>选择场景：</label>
                                <select id="parallelScenario" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;" onchange="updateParallelScenarioInfo()">
                                    <option value="">-- 请选择一个场景 --</option>
                                    <option value="multi_perspective">🔍 多角度分析 - 从多个角度分析问题</option>
                                    <option value="translation">🌍 并行翻译 - 同时翻译成多种语言</option>
                                    <option value="content_gen">📝 并行内容生成 - 同时生成文档各章节</option>
                                    <option value="code_review">👨‍💻 并行代码审查 - 多维度代码审查</option>
                                    <option value="research">🔬 并行研究 - 研究问题的多个方面</option>
                                    <option value="consensus">🤝 共识生成 - 多次生成寻找最佳答案</option>
                                </select>
                            </div>
                            
                            <div class="form-group" style="margin-bottom: 0;">
                                <label>并行策略：</label>
                                <select id="parallelStrategy" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;">
                                    <option value="full_parallel">🌐 全并行（推荐）</option>
                                    <option value="batch_parallel">📦 批量并行</option>
                                    <option value="pipeline">🔀 流水线</option>
                                    <option value="vote">🗳️ 投票</option>
                                    <option value="ensemble">🎯 集成</option>
                                </select>
                            </div>
                            
                            <div class="form-group" style="margin-bottom: 0;">
                                <label>聚合方法：</label>
                                <select id="parallelAggregation" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;">
                                    <option value="summarize">📊 总结（推荐）</option>
                                    <option value="merge">🔗 合并</option>
                                    <option value="concat">📝 连接</option>
                                    <option value="consensus">🤝 共识</option>
                                    <option value="vote">🗳️ 投票</option>
                                    <option value="best">⭐ 最佳</option>
                                    <option value="first">⚡ 第一个</option>
                                </select>
                            </div>
                        </div>

                        <!-- 场景信息 -->
                        <div id="parallelScenarioInfo" style="display: none; background: #f8f9fa; padding: 16px; border-radius: 8px; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #495057;">场景信息</h4>
                            <div id="parallelDescription" style="margin-bottom: 12px; color: #6c757d;"></div>
                            <div id="parallelHint" style="font-size: 13px; color: #6c757d; font-style: italic;"></div>
                        </div>

                        <div class="form-group">
                            <label id="parallelInputLabel">输入内容：</label>
                            <textarea id="parallelInput" placeholder="请先选择一个场景..." rows="6" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px; font-family: inherit; resize: vertical;"></textarea>
                        </div>

                        <div style="display: flex; gap: 10px;">
                            <button class="btn btn-primary" onclick="executeParallelization()" id="parallelExecuteBtn" style="flex: 1;">
                                <span>🚀 执行并行任务</span>
                            </button>
                            <button class="btn btn-secondary" onclick="clearParallelResult()">
                                🗑️ 清除结果
                            </button>
                        </div>
                    </div>

                    <!-- 执行进度 -->
                    <div class="rag-card" style="grid-column: 1 / -1; display: none;" id="parallelProgressCard">
                        <h3>⏳ 执行进度</h3>
                        <div id="parallelProgressInfo" style="margin-bottom: 16px;">
                            <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                                <span id="parallelProgressText" style="font-size: 14px; color: #495057;">正在并行执行任务...</span>
                                <span id="parallelProgressCount" style="font-size: 13px; color: #6c757d;">0 / 0</span>
                            </div>
                            <div style="background: #e9ecef; height: 8px; border-radius: 4px; overflow: hidden;">
                                <div id="parallelProgressBar" style="background: linear-gradient(90deg, #667eea, #764ba2); height: 100%; width: 0%; transition: width 0.3s;"></div>
                            </div>
                        </div>
                        
                        <!-- 任务完成状态 -->
                        <div id="parallelTaskStatus" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 8px;"></div>
                    </div>

                    <!-- 执行结果 -->
                    <div class="rag-card" style="grid-column: 1 / -1; display: none;" id="parallelResultCard">
                        <h3>📊 执行结果</h3>
                        
                        <!-- 性能统计 -->
                        <div id="parallelStats" style="background: #e7f5ff; padding: 16px; border-radius: 8px; margin-bottom: 20px;"></div>
                        
                        <!-- 聚合结果 -->
                        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; border-left: 4px solid #667eea; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #495057;">✨ 聚合结果</h4>
                            <div id="parallelAggregatedResult" class="markdown-content"></div>
                        </div>
                        
                        <!-- 各任务详细结果（可折叠） -->
                        <div>
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                                <h4 style="margin: 0; color: #495057;">📋 各任务详细结果</h4>
                                <button class="btn btn-sm btn-secondary" onclick="toggleAllParallelTasks()" id="toggleAllTasksBtn">
                                    展开全部
                                </button>
                            </div>
                            <div id="parallelTaskResults"></div>
                        </div>
                        
                        <!-- 操作按钮 -->
                        <div style="display: flex; gap: 10px; margin-top: 16px;">
                            <button class="btn btn-secondary" onclick="copyParallelResult()">
                                📋 复制结果
                            </button>
                            <button class="btn btn-secondary" onclick="downloadParallelResult()">
                                💾 下载结果
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Prompt Chaining 标签页 -->
            <div id="promptingTab" class="tab-content">
                <div class="rag-section scrollbar">
                    <!-- 场景选择 -->
                    <div class="rag-card" style="grid-column: 1 / -1;">
                        <h3>🔗 Prompt Chaining - 提示链</h3>
                        <p style="font-size: 14px; color: #6c757d; margin-bottom: 20px;">
                            将复杂任务分解为多个步骤，每个步骤专注于特定目标，前一步的输出作为下一步的输入，实现模块化、高质量的输出
                        </p>
                        
                        <div class="form-group">
                            <label>选择场景：</label>
                            <select id="chainType" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;" onchange="updateChainInfo()">
                                <option value="">-- 请选择一个场景 --</option>
                                <option value="document_gen">📄 文档生成 - 自动生成技术文档</option>
                                <option value="code_review">🔍 代码审查 - 系统化代码审查流程</option>
                                <option value="research">🔬 研究规划 - 问题到计划转化</option>
                                <option value="story">📖 故事创作 - 创意写作工作流</option>
                                <option value="product">💡 产品分析 - 需求分析和规划</option>
                            </select>
                        </div>

                        <!-- 场景信息展示 -->
                        <div id="chainInfo" style="display: none; background: #f8f9fa; padding: 16px; border-radius: 8px; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #495057;">场景信息</h4>
                            <div id="chainDescription" style="margin-bottom: 12px; color: #6c757d;"></div>
                            <div id="chainSteps" style="margin-bottom: 12px;"></div>
                            <div id="chainHint" style="font-size: 13px; color: #6c757d; font-style: italic;"></div>
                        </div>

                        <div class="form-group">
                            <label id="inputLabel">输入内容：</label>
                            <textarea id="chainInput" placeholder="请先选择一个场景..." rows="8" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px; font-family: inherit; resize: vertical;"></textarea>
                        </div>

                        <div style="display: flex; gap: 10px;">
                            <button class="btn btn-primary" onclick="runPromptChain()" id="runChainBtn" style="flex: 1;">
                                <span>▶️ 运行提示链</span>
                            </button>
                            <button class="btn btn-secondary" onclick="clearChainResult()">
                                🗑️ 清除结果
                            </button>
                        </div>
                    </div>

                    <!-- 执行结果展示 -->
                    <div class="rag-card" style="grid-column: 1 / -1; display: none;" id="chainResultCard">
                        <h3>📊 执行结果</h3>
                        
                        <!-- 进度展示 -->
                        <div id="chainProgress" style="display: none; margin-bottom: 20px;">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                                <span id="currentStep" style="font-weight: 500; color: #495057;"></span>
                                <span id="stepCounter" style="font-size: 13px; color: #6c757d;"></span>
                            </div>
                            <div style="background: #e9ecef; height: 8px; border-radius: 4px; overflow: hidden;">
                                <div id="progressBar" style="background: linear-gradient(90deg, #667eea, #764ba2); height: 100%; width: 0%; transition: width 0.3s;"></div>
                            </div>
                        </div>

                        <!-- 步骤详情（可折叠） -->
                        <div id="chainStepsDetails" style="margin-bottom: 20px;"></div>

                        <!-- 最终输出 -->
                        <div id="chainFinalOutput" style="background: #f8f9fa; padding: 20px; border-radius: 8px; border-left: 4px solid #667eea;">
                            <h4 style="margin-bottom: 12px; color: #495057;">✨ 最终输出</h4>
                            <div id="finalOutputContent" class="markdown-content"></div>
                        </div>

                        <!-- 执行信息 -->
                        <div id="chainMetadata" style="margin-top: 16px; padding: 12px; background: #e7f5ff; border-radius: 8px; font-size: 13px; color: #495057;">
                            <!-- 元数据将通过 JavaScript 填充 -->
                        </div>

                        <!-- 操作按钮 -->
                        <div style="display: flex; gap: 10px; margin-top: 16px;">
                            <button class="btn btn-secondary" onclick="copyChainResult()">
                                📋 复制结果
                            </button>
                            <button class="btn btn-secondary" onclick="downloadChainResult()">
                                💾 下载结果
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Reflection Agent 标签页 -->
            <div id="reflectionTab" class="tab-content">
                <div class="rag-section scrollbar">
                    <!-- 场景选择 -->
                    <div class="rag-card" style="grid-column: 1 / -1;">
                        <h3>💭 Reflection Agent - 反思智能体</h3>
                        <p style="font-size: 14px; color: #6c757d; margin-bottom: 20px;">
                            通过自我批判和迭代改进来提升输出质量。系统先生成初始响应，然后进行反思，基于反思进行改进，可进行多轮迭代直到达到质量要求。
                        </p>
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 20px;">
                            <div class="form-group" style="margin-bottom: 0;">
                                <label>选择场景：</label>
                                <select id="reflectionScenario" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;" onchange="updateReflectionScenarioInfo()">
                                    <option value="">-- 请选择一个场景 --</option>
                                    <option value="content">📝 内容创作 - 文章、博客、报告</option>
                                    <option value="code">💻 代码优化 - 代码质量提升</option>
                                    <option value="analysis">📊 分析报告 - 数据分析和洞察</option>
                                    <option value="translation">🌍 翻译优化 - 翻译质量改进</option>
                                </select>
                            </div>
                            
                            <div class="form-group" style="margin-bottom: 0;">
                                <label>反思策略：</label>
                                <select id="reflectionStrategy" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;" onchange="updateReflectionStrategyInfo()">
                                    <option value="simple">💡 简单反思 - 单一批评者</option>
                                    <option value="multi_aspect" selected>🎯 多维度反思（推荐）- 全面评估</option>
                                    <option value="debate">⚖️ 辩论式反思 - 正反两方</option>
                                    <option value="expert">👨‍🔬 专家反思 - 领域专家评估</option>
                                </select>
                            </div>
                        </div>

                        <!-- 场景信息 -->
                        <div id="reflectionScenarioInfo" style="display: none; background: #f8f9fa; padding: 16px; border-radius: 8px; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #495057;">场景信息</h4>
                            <div id="reflectionDescription" style="margin-bottom: 12px; color: #6c757d;"></div>
                            <div id="reflectionCriteria" style="margin-bottom: 12px;"></div>
                            <div id="reflectionHint" style="font-size: 13px; color: #6c757d; font-style: italic;"></div>
                        </div>

                        <!-- 专家设置（仅在expert策略时显示） -->
                        <div id="expertSettings" style="display: none; background: #fff3cd; padding: 16px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #ffc107;">
                            <h4 style="margin-bottom: 12px; color: #856404;">👨‍🔬 专家设置</h4>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                                <div class="form-group" style="margin-bottom: 0;">
                                    <label style="color: #856404;">专家角色：</label>
                                    <input type="text" id="expertRole" placeholder="例如：资深Python开发工程师" style="width: 100%; padding: 10px; border: 2px solid #dee2e6; border-radius: 6px; font-size: 14px;">
                                </div>
                                <div class="form-group" style="margin-bottom: 0;">
                                    <label style="color: #856404;">专业领域：</label>
                                    <input type="text" id="expertExpertise" placeholder="例如：10年Python和架构设计经验" style="width: 100%; padding: 10px; border: 2px solid #dee2e6; border-radius: 6px; font-size: 14px;">
                                </div>
                            </div>
                        </div>

                        <!-- 高级设置 -->
                        <div style="background: #e7f5ff; padding: 16px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #0c63e4;">
                            <h4 style="margin-bottom: 12px; color: #084298;">⚙️ 高级设置</h4>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                                <div class="form-group" style="margin-bottom: 0;">
                                    <label style="color: #084298;">最大迭代次数：</label>
                                    <input type="number" id="maxIterations" value="3" min="1" max="10" style="width: 100%; padding: 10px; border: 2px solid #dee2e6; border-radius: 6px; font-size: 14px;">
                                </div>
                                <div class="form-group" style="margin-bottom: 0;">
                                    <label style="color: #084298;">质量阈值（0.0-1.0）：</label>
                                    <input type="number" id="scoreThreshold" value="0.85" min="0" max="1" step="0.05" style="width: 100%; padding: 10px; border: 2px solid #dee2e6; border-radius: 6px; font-size: 14px;">
                                </div>
                            </div>
                            <p style="margin-top: 8px; font-size: 12px; color: #6c757d;">达到质量阈值后将自动停止迭代</p>
                        </div>

                        <div class="form-group">
                            <label id="reflectionInputLabel">任务描述或初始内容：</label>
                            <textarea id="reflectionInput" placeholder="请先选择一个场景..." rows="8" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px; font-family: inherit; resize: vertical;"></textarea>
                            <p style="margin-top: 8px; font-size: 12px; color: #6c757d;">💡 提示：如果输入的是任务描述，系统会先生成初始内容再进行反思；如果输入的是已有内容，系统会直接对其进行反思和改进。</p>
                        </div>

                        <div style="display: flex; gap: 10px;">
                            <button class="btn btn-primary" onclick="executeReflection()" id="reflectionExecuteBtn" style="flex: 1;">
                                <span>💭 开始反思与改进</span>
                            </button>
                            <button class="btn btn-secondary" onclick="clearReflectionResult()">
                                🗑️ 清除结果
                            </button>
                        </div>
                    </div>

                    <!-- 执行进度 -->
                    <div class="rag-card" style="grid-column: 1 / -1; display: none;" id="reflectionProgressCard">
                        <h3>⏳ 反思进度</h3>
                        <div id="reflectionProgressInfo" style="margin-bottom: 16px;">
                            <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                                <span id="reflectionProgressText" style="font-size: 14px; color: #495057;">正在执行反思...</span>
                                <span id="reflectionIterationCount" style="font-size: 13px; color: #6c757d;">第 0 轮</span>
                            </div>
                            <div style="background: #e9ecef; height: 8px; border-radius: 4px; overflow: hidden;">
                                <div id="reflectionProgressBar" style="background: linear-gradient(90deg, #667eea, #764ba2); height: 100%; width: 0%; transition: width 0.3s;"></div>
                            </div>
                        </div>
                        
                        <!-- 当前步骤 -->
                        <div id="reflectionCurrentStep" style="background: #f8f9fa; padding: 16px; border-radius: 8px; border-left: 4px solid #667eea;">
                            <h4 style="margin-bottom: 8px; color: #495057;">当前步骤</h4>
                            <p id="reflectionStepMessage" style="margin: 0; color: #6c757d;">准备开始...</p>
                        </div>
                    </div>

                    <!-- 反思历史 -->
                    <div class="rag-card" style="grid-column: 1 / -1; display: none;" id="reflectionHistoryCard">
                        <h3>📜 反思历史</h3>
                        <div id="reflectionHistory" style="display: flex; flex-direction: column; gap: 16px;"></div>
                    </div>

                    <!-- 最终结果 -->
                    <div class="rag-card" style="grid-column: 1 / -1; display: none;" id="reflectionResultCard">
                        <h3>✨ 最终结果</h3>
                        
                        <!-- 质量提升统计 -->
                        <div id="reflectionStats" style="background: #d1f4e0; padding: 16px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #28a745;">
                            <div style="display: flex; justify-content: space-around; text-align: center;">
                                <div>
                                    <div style="font-size: 24px; font-weight: 600; color: #155724;" id="finalScore">0.00</div>
                                    <div style="font-size: 13px; color: #6c757d;">最终评分</div>
                                </div>
                                <div>
                                    <div style="font-size: 24px; font-weight: 600; color: #155724;" id="totalIterations">0</div>
                                    <div style="font-size: 13px; color: #6c757d;">迭代次数</div>
                                </div>
                                <div>
                                    <div style="font-size: 24px; font-weight: 600; color: #155724;" id="scoreImprovement">+0.00</div>
                                    <div style="font-size: 13px; color: #6c757d;">质量提升</div>
                                </div>
                                <div>
                                    <div style="font-size: 24px; font-weight: 600; color: #155724;" id="reflectionTime">0.0s</div>
                                    <div style="font-size: 13px; color: #6c757d;">总耗时</div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 最终内容 -->
                        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; border-left: 4px solid #667eea; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #495057;">📝 优化后的内容</h4>
                            <div id="reflectionFinalContent" class="markdown-content"></div>
                        </div>

                        <!-- 改进总结 -->
                        <div style="background: #fff3cd; padding: 20px; border-radius: 8px; border-left: 4px solid #ffc107; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #856404;">💡 改进总结</h4>
                            <div id="reflectionSummary" class="markdown-content"></div>
                        </div>
                        
                        <!-- 操作按钮 -->
                        <div style="display: flex; gap: 10px;">
                            <button class="btn btn-secondary" onclick="copyReflectionResult()">
                                📋 复制结果
                            </button>
                            <button class="btn btn-secondary" onclick="downloadReflectionResult()">
                                💾 下载结果
                            </button>
                            <button class="btn btn-secondary" onclick="showReflectionHistory()">
                                📜 查看完整历史
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tool Use Agent 标签页 -->
            <div id="tooluseTab" class="tab-content">
                <div class="rag-section scrollbar">
                    <!-- 场景选择 -->
                    <div class="rag-card" style="grid-column: 1 / -1;">
                        <h3>🔧 Tool Use Agent - 工具使用智能体</h3>
                        <p style="font-size: 14px; color: #6c757d; margin-bottom: 20px;">
                            智能选择和执行工具来完成复杂任务。系统会分析用户需求，自动选择最合适的工具，并支持多工具协作完成复杂任务。
                        </p>
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 20px;">
                            <div class="form-group" style="margin-bottom: 0;">
                                <label>工具类型过滤：</label>
                                <select id="toolTypeFilter" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;" onchange="updateToolTypeInfo()">
                                    <option value="">-- 所有工具类型 --</option>
                                    <option value="file_operation">📁 文件操作</option>
                                    <option value="network_request">🌐 网络请求</option>
                                    <option value="data_processing">📊 数据处理</option>
                                    <option value="system_info">💻 系统信息</option>
                                    <option value="calculation">🧮 计算工具</option>
                                    <option value="text_processing">📝 文本处理</option>
                                </select>
                            </div>
                            
                            <div class="form-group" style="margin-bottom: 0;">
                                <label>最大迭代次数：</label>
                                <select id="maxIterations" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;">
                                    <option value="1">1次 - 单次工具调用</option>
                                    <option value="3">3次 - 简单任务链</option>
                                    <option value="5" selected>5次 - 复杂任务（推荐）</option>
                                    <option value="10">10次 - 极复杂任务</option>
                                </select>
                            </div>
                        </div>

                        <!-- 工具类型信息 -->
                        <div id="toolTypeInfo" style="display: none; background: #f8f9fa; padding: 16px; border-radius: 8px; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #495057;">工具类型信息</h4>
                            <div id="toolTypeDescription" style="margin-bottom: 12px; color: #6c757d;"></div>
                            <div id="toolTypeExamples" style="margin-bottom: 12px;"></div>
                        </div>

                        <!-- 快速场景选择 -->
                        <div style="background: #e7f3ff; padding: 16px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #007bff;">
                            <h4 style="margin-bottom: 12px; color: #004085;">🚀 快速场景</h4>
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 8px;">
                                <button class="btn btn-outline" onclick="setQuickTask('读取config.json文件内容')" style="text-align: left; font-size: 13px;">
                                    📁 读取配置文件
                                </button>
                                <button class="btn btn-outline" onclick="setQuickTask('获取https://api.github.com的状态')" style="text-align: left; font-size: 13px;">
                                    🌐 检查API状态
                                </button>
                                <button class="btn btn-outline" onclick="setQuickTask('计算1到100的平均值')" style="text-align: left; font-size: 13px;">
                                    🧮 数学计算
                                </button>
                                <button class="btn btn-outline" onclick="setQuickTask('获取当前系统CPU和内存使用情况')" style="text-align: left; font-size: 13px;">
                                    💻 系统监控
                                </button>
                                <button class="btn btn-outline" onclick="setQuickTask('分析这段文本的字数和句子数：Hello world. This is a test.')" style="text-align: left; font-size: 13px;">
                                    📝 文本分析
                                </button>
                                <button class="btn btn-outline" onclick="setQuickTask('将100米转换为英尺')" style="text-align: left; font-size: 13px;">
                                    🔄 单位转换
                                </button>
                            </div>
                        </div>
                        
                        <!-- 输入区域 -->
                        <div class="form-group">
                            <label>任务描述：</label>
                            <textarea 
                                id="toolUseInput" 
                                placeholder="请描述您需要完成的任务，例如：&#10;- 读取某个文件的内容&#10;- 获取某个网站的状态&#10;- 计算一些数据的统计信息&#10;- 分析文本内容&#10;- 转换单位或格式&#10;&#10;系统会自动选择合适的工具来完成您的任务。"
                                style="width: 100%; height: 120px; padding: 15px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px; resize: vertical;"
                            ></textarea>
                        </div>
                        
                        <!-- 执行按钮 -->
                        <div style="display: flex; gap: 10px; margin-bottom: 20px;">
                            <button class="btn btn-primary" onclick="executeToolUse()" id="toolUseExecuteBtn">
                                🔧 执行任务
                            </button>
                            <button class="btn btn-secondary" onclick="executeToolUseStream()" id="toolUseStreamBtn">
                                📡 流式执行
                            </button>
                            <button class="btn btn-secondary" onclick="showAvailableTools()">
                                🛠️ 查看可用工具
                            </button>
                            <button class="btn btn-secondary" onclick="showToolHistory()">
                                📊 执行历史
                            </button>
                            <button class="btn btn-outline" onclick="clearToolUseResult()">
                                🧹 清除结果
                            </button>
                        </div>
                    </div>

                    <!-- 进度显示 -->
                    <div id="toolUseProgressCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">⚡ 执行进度</h4>
                        <div style="background: #f8f9fa; border-radius: 8px; padding: 4px; margin-bottom: 16px;">
                            <div id="toolUseProgressBar" style="background: linear-gradient(90deg, #667eea, #764ba2); height: 8px; border-radius: 4px; width: 0%; transition: width 0.3s;"></div>
                        </div>
                        <div id="toolUseCurrentStep" style="color: #6c757d; font-size: 14px;">准备执行...</div>
                    </div>

                    <!-- 工具执行历史 -->
                    <div id="toolUseHistoryCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">📋 执行步骤</h4>
                        <div id="toolUseHistory" style="max-height: 400px; overflow-y: auto;" class="scrollbar"></div>
                    </div>

                    <!-- 执行结果 -->
                    <div id="toolUseResultCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">✅ 执行结果</h4>
                        
                        <!-- 统计信息 -->
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; margin-bottom: 20px;">
                            <div style="background: #d1f4e0; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #155724;" id="toolUseSuccess">-</div>
                                <div style="font-size: 12px; color: #155724;">执行状态</div>
                            </div>
                            <div style="background: #cce7ff; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #004085;" id="toolUseIterations">-</div>
                                <div style="font-size: 12px; color: #004085;">执行轮次</div>
                            </div>
                            <div style="background: #fff3cd; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #856404;" id="toolUseToolsUsed">-</div>
                                <div style="font-size: 12px; color: #856404;">使用工具</div>
                            </div>
                            <div style="background: #f8d7da; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #721c24;" id="toolUseTime">-</div>
                                <div style="font-size: 12px; color: #721c24;">总耗时</div>
                            </div>
                        </div>

                        <!-- 最终结果 -->
                        <div style="background: #d1f4e0; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #155724;">🎯 最终结果</h4>
                            <div id="toolUseFinalResult" class="markdown-content"></div>
                        </div>
                        
                        <!-- 操作按钮 -->
                        <div style="display: flex; gap: 10px;">
                            <button class="btn btn-secondary" onclick="copyToolUseResult()">
                                📋 复制结果
                            </button>
                            <button class="btn btn-secondary" onclick="downloadToolUseResult()">
                                💾 下载结果
                            </button>
                            <button class="btn btn-secondary" onclick="showToolUseHistory()">
                                📜 查看详细历史
                            </button>
                        </div>
                    </div>

                    <!-- 可用工具列表 -->
                    <div id="availableToolsCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">🛠️ 可用工具</h4>
                        <div id="availableToolsList" style="max-height: 500px; overflow-y: auto;" class="scrollbar"></div>
                    </div>
                </div>
            </div>

            <!-- Planning Agent 标签页 -->
            <div id="planningTab" class="tab-content">
                <div class="rag-section scrollbar">
                    <!-- 场景选择 -->
                    <div class="rag-card" style="grid-column: 1 / -1;">
                        <h3>📋 Planning Agent - 规划智能体</h3>
                        <p style="font-size: 14px; color: #6c757d; margin-bottom: 20px;">
                            智能分析目标并制定详细的执行计划。系统会将复杂目标分解为可执行的子任务，制定合理的执行顺序，并支持动态调整和进度监控。
                        </p>
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 20px;">
                            <div class="form-group" style="margin-bottom: 0;">
                                <label>预定义场景：</label>
                                <select id="planningScenario" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;" onchange="updatePlanningScenarioInfo()">
                                    <option value="">-- 自定义规划 --</option>
                                    <option value="software_development">💻 软件开发项目</option>
                                    <option value="research_project">🔬 研究项目</option>
                                    <option value="product_launch">🚀 产品发布</option>
                                    <option value="learning_project">📚 学习项目</option>
                                </select>
                            </div>
                            
                            <div class="form-group" style="margin-bottom: 0;">
                                <label>执行策略：</label>
                                <select id="planningStrategy" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;">
                                    <option value="adaptive">🎯 自适应（推荐）</option>
                                    <option value="sequential">📝 顺序执行</option>
                                    <option value="parallel">⚡ 并行执行</option>
                                    <option value="dependency_based">🔗 依赖关系</option>
                                </select>
                            </div>
                        </div>

                        <!-- 场景信息 -->
                        <div id="planningScenarioInfo" style="display: none; background: #f8f9fa; padding: 16px; border-radius: 8px; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #495057;">场景信息</h4>
                            <div id="planningScenarioDescription" style="margin-bottom: 12px; color: #6c757d;"></div>
                            <div id="planningScenarioFeatures" style="margin-bottom: 12px;"></div>
                        </div>

                        <!-- 快速场景选择 -->
                        <div style="background: #e7f3ff; padding: 16px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #007bff;">
                            <h4 style="margin-bottom: 12px; color: #004085;">🚀 快速场景</h4>
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 8px;">
                                <button class="btn btn-outline" onclick="setQuickPlanning('开发一个在线购物网站')" style="text-align: left; font-size: 13px;">
                                    💻 Web开发项目
                                </button>
                                <button class="btn btn-outline" onclick="setQuickPlanning('研究人工智能在教育中的应用')" style="text-align: left; font-size: 13px;">
                                    🔬 AI研究项目
                                </button>
                                <button class="btn btn-outline" onclick="setQuickPlanning('推出新的移动应用产品')" style="text-align: left; font-size: 13px;">
                                    🚀 产品上市
                                </button>
                                <button class="btn btn-outline" onclick="setQuickPlanning('学习Python机器学习')" style="text-align: left; font-size: 13px;">
                                    📚 技能学习
                                </button>
                                <button class="btn btn-outline" onclick="setQuickPlanning('组织公司年会活动')" style="text-align: left; font-size: 13px;">
                                    🎉 活动策划
                                </button>
                                <button class="btn btn-outline" onclick="setQuickPlanning('建立团队知识管理系统')" style="text-align: left; font-size: 13px;">
                                    📖 知识管理
                                </button>
                            </div>
                        </div>
                        
                        <!-- 输入区域 -->
                        <div class="form-group">
                            <label>目标描述：</label>
                            <textarea 
                                id="planningGoal" 
                                placeholder="请描述您的目标，例如：&#10;- 开发一个电商网站&#10;- 研究某个技术领域&#10;- 学习新的技能&#10;- 推出新产品&#10;- 组织活动或项目&#10;&#10;系统会自动分析目标并制定详细的执行计划。"
                                style="width: 100%; height: 120px; padding: 15px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px; resize: vertical;"
                            ></textarea>
                        </div>

                        <!-- 高级选项 -->
                        <div style="background: #f8f9fa; padding: 16px; border-radius: 8px; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #495057;">⚙️ 高级选项</h4>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                <div>
                                    <label style="display: flex; align-items: center; gap: 8px; font-size: 14px; color: #495057;">
                                        <input type="checkbox" id="autoExecute" style="margin: 0;">
                                        自动执行计划
                                    </label>
                                    <div style="font-size: 12px; color: #6c757d; margin-top: 4px;">创建计划后立即开始执行</div>
                                </div>
                                <div>
                                    <label style="display: flex; align-items: center; gap: 8px; font-size: 14px; color: #495057;">
                                        <input type="checkbox" id="streamExecution" style="margin: 0;">
                                        流式执行
                                    </label>
                                    <div style="font-size: 12px; color: #6c757d; margin-top: 4px;">实时显示执行进度</div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 执行按钮 -->
                        <div style="display: flex; gap: 10px; margin-bottom: 20px;">
                            <button class="btn btn-primary" onclick="createPlanning()" id="planningCreateBtn">
                                📋 创建计划
                            </button>
                            <button class="btn btn-secondary" onclick="showPlanningScenarios()">
                                🎯 查看场景
                            </button>
                            <button class="btn btn-secondary" onclick="showAllPlans()">
                                📊 所有计划
                            </button>
                            <button class="btn btn-outline" onclick="clearPlanningResult()">
                                🧹 清除结果
                            </button>
                        </div>
                    </div>

                    <!-- 进度显示 -->
                    <div id="planningProgressCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">⚡ 创建进度</h4>
                        <div style="background: #f8f9fa; border-radius: 8px; padding: 4px; margin-bottom: 16px;">
                            <div id="planningProgressBar" style="background: linear-gradient(90deg, #667eea, #764ba2); height: 8px; border-radius: 4px; width: 0%; transition: width 0.3s;"></div>
                        </div>
                        <div id="planningCurrentStep" style="color: #6c757d; font-size: 14px;">准备创建计划...</div>
                    </div>

                    <!-- 计划详情 -->
                    <div id="planningDetailCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">📋 计划详情</h4>
                        
                        <!-- 计划基本信息 -->
                        <div style="background: #e7f3ff; padding: 16px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #007bff;">
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                <div>
                                    <div style="font-size: 14px; color: #004085; margin-bottom: 4px;">计划名称</div>
                                    <div id="planName" style="font-weight: 600; color: #495057;">-</div>
                                </div>
                                <div>
                                    <div style="font-size: 14px; color: #004085; margin-bottom: 4px;">执行策略</div>
                                    <div id="planStrategy" style="font-weight: 600; color: #495057;">-</div>
                                </div>
                            </div>
                            <div style="margin-top: 12px;">
                                <div style="font-size: 14px; color: #004085; margin-bottom: 4px;">计划描述</div>
                                <div id="planDescription" style="color: #495057;">-</div>
                            </div>
                        </div>

                        <!-- 任务统计 -->
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; margin-bottom: 20px;">
                            <div style="background: #d1f4e0; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #155724;" id="totalTasks">-</div>
                                <div style="font-size: 12px; color: #155724;">总任务数</div>
                            </div>
                            <div style="background: #cce7ff; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #004085;" id="estimatedHours">-</div>
                                <div style="font-size: 12px; color: #004085;">预计时长</div>
                            </div>
                            <div style="background: #fff3cd; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #856404;" id="planProgress">0%</div>
                                <div style="font-size: 12px; color: #856404;">完成进度</div>
                            </div>
                            <div style="background: #f8d7da; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #721c24;" id="planStatus">待执行</div>
                                <div style="font-size: 12px; color: #721c24;">计划状态</div>
                            </div>
                        </div>

                        <!-- 任务列表 -->
                        <div style="background: #f8f9fa; padding: 16px; border-radius: 8px; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #495057;">📝 任务列表</h4>
                            <div id="tasksList" style="max-height: 400px; overflow-y: auto;" class="scrollbar"></div>
                        </div>
                        
                        <!-- 操作按钮 -->
                        <div style="display: flex; gap: 10px;">
                            <button class="btn btn-primary" onclick="executePlan()" id="executePlanBtn" style="display: none;">
                                ▶️ 执行计划
                            </button>
                            <button class="btn btn-secondary" onclick="executePlanStream()" id="executePlanStreamBtn" style="display: none;">
                                📡 流式执行
                            </button>
                            <button class="btn btn-secondary" onclick="copyPlanResult()">
                                📋 复制计划
                            </button>
                            <button class="btn btn-secondary" onclick="downloadPlanResult()">
                                💾 下载计划
                            </button>
                            <button class="btn btn-danger" onclick="deletePlan()" id="deletePlanBtn" style="display: none;">
                                🗑️ 删除计划
                            </button>
                        </div>
                    </div>

                    <!-- 执行进度 -->
                    <div id="executionProgressCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">⚡ 执行进度</h4>
                        <div style="background: #f8f9fa; border-radius: 8px; padding: 4px; margin-bottom: 16px;">
                            <div id="executionProgressBar" style="background: linear-gradient(90deg, #28a745, #20c997); height: 8px; border-radius: 4px; width: 0%; transition: width 0.3s;"></div>
                        </div>
                        <div id="executionCurrentTask" style="color: #6c757d; font-size: 14px;">准备执行...</div>
                    </div>

                    <!-- 执行日志 -->
                    <div id="executionLogCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">📋 执行日志</h4>
                        <div id="executionLog" style="max-height: 400px; overflow-y: auto;" class="scrollbar"></div>
                    </div>

                    <!-- 执行结果 -->
                    <div id="planningResultCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">✅ 执行结果</h4>
                        
                        <!-- 执行统计 -->
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; margin-bottom: 20px;">
                            <div style="background: #d1f4e0; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #155724;" id="executionSuccess">-</div>
                                <div style="font-size: 12px; color: #155724;">执行状态</div>
                            </div>
                            <div style="background: #cce7ff; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #004085;" id="completedTasks">-</div>
                                <div style="font-size: 12px; color: #004085;">完成任务</div>
                            </div>
                            <div style="background: #fff3cd; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #856404;" id="failedTasks">-</div>
                                <div style="font-size: 12px; color: #856404;">失败任务</div>
                            </div>
                            <div style="background: #f8d7da; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #721c24;" id="executionDuration">-</div>
                                <div style="font-size: 12px; color: #721c24;">执行时长</div>
                            </div>
                        </div>

                        <!-- 最终结果 -->
                        <div style="background: #d1f4e0; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #155724;">🎯 执行总结</h4>
                            <div id="planningFinalResult" class="markdown-content"></div>
                        </div>
                        
                        <!-- 操作按钮 -->
                        <div style="display: flex; gap: 10px;">
                            <button class="btn btn-secondary" onclick="copyPlanningResult()">
                                📋 复制结果
                            </button>
                            <button class="btn btn-secondary" onclick="downloadPlanningResult()">
                                💾 下载结果
                            </button>
                            <button class="btn btn-secondary" onclick="showPlanningLog()">
                                📜 查看详细日志
                            </button>
                        </div>
                    </div>

                    <!-- 场景列表 -->
                    <div id="scenarioListCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">🎯 预定义场景</h4>
                        <div id="scenarioList" style="max-height: 500px; overflow-y: auto;" class="scrollbar"></div>
                    </div>

                    <!-- 所有计划列表 -->
                    <div id="allPlansCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">📊 所有计划</h4>
                        <div id="allPlansList" style="max-height: 500px; overflow-y: auto;" class="scrollbar"></div>
                    </div>
                </div>
            </div>

            <!-- Multi-Agent Collaboration 标签页 -->
            <div id="multiagentTab" class="tab-content">
                <div class="rag-section scrollbar">
                    <!-- 团队选择 -->
                    <div class="rag-card" style="grid-column: 1 / -1;">
                        <h3>👥 Multi-Agent Collaboration - 多智能体协作</h3>
                        <p style="font-size: 14px; color: #6c757d; margin-bottom: 20px;">
                            多个专业化的 AI Agent 组成团队，通过协作共同完成复杂任务。每个 Agent 扮演不同角色，贡献自己的专业知识，产生 1+1>2 的协同效应。
                        </p>
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 20px;">
                            <div class="form-group" style="margin-bottom: 0;">
                                <label>协作团队：</label>
                                <select id="collaborationTeam" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;" onchange="updateTeamInfo()">
                                    <option value="">-- 选择团队 --</option>
                                    <option value="software_dev">💻 软件开发团队</option>
                                    <option value="research">🔬 研究团队</option>
                                    <option value="content">📝 内容创作团队</option>
                                    <option value="business">💼 商业咨询团队</option>
                                </select>
                            </div>
                            
                            <div class="form-group" style="margin-bottom: 0;">
                                <label>协作模式：</label>
                                <select id="collaborationMode" style="width: 100%; padding: 12px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px;">
                                    <option value="hierarchical">🏢 层级协作（推荐）</option>
                                    <option value="sequential">🔄 顺序协作</option>
                                    <option value="parallel">⚡ 并行协作</option>
                                    <option value="peer_to_peer">🤝 对等协作</option>
                                    <option value="hybrid">🔀 混合模式</option>
                                </select>
                            </div>
                        </div>

                        <!-- 团队信息 -->
                        <div id="teamInfoCard" style="display: none; background: #f8f9fa; padding: 16px; border-radius: 8px; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #495057;">团队信息</h4>
                            <div id="teamDescription" style="margin-bottom: 12px; color: #6c757d;"></div>
                            <div id="teamAgents" style="margin-bottom: 12px;"></div>
                            <div id="teamUseCases"></div>
                        </div>

                        <!-- 快速任务示例 -->
                        <div style="background: #e7f3ff; padding: 16px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #007bff;">
                            <h4 style="margin-bottom: 12px; color: #004085;">🚀 快速任务</h4>
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 8px;">
                                <button class="btn btn-outline" onclick="setQuickCollaboration('设计并实现一个在线聊天应用', 'software_dev')" style="text-align: left; font-size: 13px;">
                                    💻 开发聊天应用
                                </button>
                                <button class="btn btn-outline" onclick="setQuickCollaboration('研究深度学习在自然语言处理中的应用', 'research')" style="text-align: left; font-size: 13px;">
                                    🔬 NLP研究
                                </button>
                                <button class="btn btn-outline" onclick="setQuickCollaboration('撰写一篇关于人工智能未来发展的文章', 'content')" style="text-align: left; font-size: 13px;">
                                    📝 AI文章创作
                                </button>
                                <button class="btn btn-outline" onclick="setQuickCollaboration('分析企业数字化转型策略', 'business')" style="text-align: left; font-size: 13px;">
                                    💼 数字化转型咨询
                                </button>
                                <button class="btn btn-outline" onclick="setQuickCollaboration('设计一个电商平台的系统架构', 'software_dev')" style="text-align: left; font-size: 13px;">
                                    🏗️ 电商架构设计
                                </button>
                                <button class="btn btn-outline" onclick="setQuickCollaboration('制定产品推广和营销策略', 'content')" style="text-align: left; font-size: 13px;">
                                    📢 营销策划
                                </button>
                            </div>
                        </div>
                        
                        <!-- 输入区域 -->
                        <div class="form-group">
                            <label>任务描述：</label>
                            <textarea 
                                id="collaborationTask" 
                                placeholder="请描述需要团队协作完成的任务，例如：&#10;&#10;软件开发团队：&#10;- 设计并实现一个博客系统&#10;- 开发一个移动应用&#10;&#10;研究团队：&#10;- 研究某个科学问题&#10;- 设计实验方案&#10;&#10;内容创作团队：&#10;- 撰写技术文章&#10;- 策划营销活动&#10;&#10;商业咨询团队：&#10;- 制定商业计划&#10;- 分析市场机会"
                                style="width: 100%; height: 150px; padding: 15px; border: 2px solid #dee2e6; border-radius: 8px; font-size: 14px; resize: vertical;"
                            ></textarea>
                        </div>
                        
                        <!-- 执行按钮 -->
                        <div style="display: flex; gap: 10px; margin-bottom: 20px;">
                            <button class="btn btn-primary" onclick="startCollaboration()" id="collaborationStartBtn">
                                🚀 开始协作
                            </button>
                            <button class="btn btn-secondary" onclick="showTeamDetails()">
                                👥 查看团队
                            </button>
                            <button class="btn btn-secondary" onclick="showModeDetails()">
                                🔄 查看模式
                            </button>
                            <button class="btn btn-outline" onclick="clearCollaborationResult()">
                                🧹 清除结果
                            </button>
                        </div>
                    </div>

                    <!-- 协作进度 -->
                    <div id="collaborationProgressCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">⚡ 协作进度</h4>
                        <div id="collaborationTeamInfo" style="background: #e7f3ff; padding: 12px; border-radius: 8px; margin-bottom: 12px; border-left: 4px solid #007bff;">
                            <div style="font-weight: 600; margin-bottom: 8px;">团队信息加载中...</div>
                        </div>
                        <div id="collaborationStatus" style="color: #6c757d; font-size: 14px;">准备开始协作...</div>
                    </div>

                    <!-- Agent 贡献 -->
                    <div id="agentContributionsCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">🤖 Agent 贡献</h4>
                        <div id="agentContributionsList" style="max-height: 600px; overflow-y: auto;" class="scrollbar"></div>
                    </div>

                    <!-- 消息记录 -->
                    <div id="collaborationMessagesCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">💬 消息记录</h4>
                        <div id="messagesList" style="max-height: 400px; overflow-y: auto;" class="scrollbar"></div>
                    </div>

                    <!-- 最终结果 -->
                    <div id="collaborationResultCard" class="rag-card" style="display: none; grid-column: 1 / -1;">
                        <h4 style="margin-bottom: 16px; color: #495057;">✅ 协作结果</h4>
                        
                        <!-- 执行统计 -->
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; margin-bottom: 20px;">
                            <div style="background: #d1f4e0; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #155724;" id="collaborationSuccess">-</div>
                                <div style="font-size: 12px; color: #155724;">协作状态</div>
                            </div>
                            <div style="background: #cce7ff; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #004085;" id="agentCount">-</div>
                                <div style="font-size: 12px; color: #004085;">参与 Agent</div>
                            </div>
                            <div style="background: #fff3cd; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #856404;" id="messageCount">-</div>
                                <div style="font-size: 12px; color: #856404;">消息数量</div>
                            </div>
                            <div style="background: #f8d7da; padding: 12px; border-radius: 8px; text-align: center;">
                                <div style="font-size: 20px; font-weight: 600; color: #721c24;" id="collaborationTime">-</div>
                                <div style="font-size: 12px; color: #721c24;">协作时长</div>
                            </div>
                        </div>

                        <!-- 最终输出 -->
                        <div style="background: #d1f4e0; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745; margin-bottom: 20px;">
                            <h4 style="margin-bottom: 12px; color: #155724;">🎯 最终输出</h4>
                            <div id="collaborationFinalOutput" class="markdown-content"></div>
                        </div>
                        
                        <!-- 操作按钮 -->
                        <div style="display: flex; gap: 10px;">
                            <button class="btn btn-secondary" onclick="copyCollaborationResult()">
                                📋 复制结果
                            </button>
                            <button class="btn btn-secondary" onclick="downloadCollaborationResult()">
                                💾 下载结果
                            </button>
                            <button class="btn btn-secondary" onclick="showCollaborationDetails()">
                                📊 查看详情
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Memory Management Agent 内容 -->
            <div id="memoryTab" class="tab-content">
                <div class="rag-section scrollbar">
                    <div class="rag-card" style="grid-column: 1 / -1;">
                        <h3>🧠 Memory Management Agent - 记忆管理</h3>
                        <p style="font-size: 14px; color: #6c757d; margin-bottom: 20px;">
                            智能记忆管理系统 - 让AI拥有记忆能力，记住过去的对话、学习用户偏好、提供个性化服务
                        </p>
                        
                        <div style="display: grid; grid-template-columns: 400px 1fr; gap: 20px;">
                            <!-- 左侧：记忆管理面板 -->
                            <div style="display: flex; flex-direction: column; gap: 15px;">
                                <!-- 存储新记忆 -->
                                <div style="background: white; border-radius: 10px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                                    <h4 style="margin-bottom: 15px; color: #667eea;">📝 存储新记忆</h4>
                                    <textarea id="memoryContent" placeholder="输入记忆内容..." rows="3" style="width: 100%; padding: 10px; border: 2px solid #e0e0e0; border-radius: 5px; margin-bottom: 10px;"></textarea>
                                    
                                    <div style="margin-bottom: 10px;">
                                        <label style="font-size: 13px; color: #666; display: block; margin-bottom: 5px;">记忆类型:</label>
                                        <select id="memoryType" style="width: 100%; padding: 8px; border: 1px solid #e0e0e0; border-radius: 5px;">
                                            <option value="semantic">📚 语义记忆 (事实知识)</option>
                                            <option value="episodic">📖 情景记忆 (具体事件)</option>
                                            <option value="long_term">💾 长期记忆 (用户偏好)</option>
                                            <option value="short_term">⚡ 短期记忆 (临时信息)</option>
                                            <option value="working">🔧 工作记忆 (任务相关)</option>
                                            <option value="procedural">⚙️ 程序性记忆 (操作步骤)</option>
                                        </select>
                                    </div>
                                    
                                    <div style="margin-bottom: 10px;">
                                        <label style="font-size: 13px; color: #666; display: block; margin-bottom: 5px;">重要性:</label>
                                        <select id="memoryImportance" style="width: 100%; padding: 8px; border: 1px solid #e0e0e0; border-radius: 5px;">
                                            <option value="5">⭐⭐⭐⭐⭐ 关键</option>
                                            <option value="4">⭐⭐⭐⭐ 高</option>
                                            <option value="3" selected>⭐⭐⭐ 中</option>
                                            <option value="2">⭐⭐ 低</option>
                                            <option value="1">⭐ 最低</option>
                                        </select>
                                    </div>
                                    
                                    <div style="margin-bottom: 10px;">
                                        <label style="font-size: 13px; color: #666; display: block; margin-bottom: 5px;">标签 (逗号分隔):</label>
                                        <input type="text" id="memoryTags" placeholder="例如: 用户偏好, Python, 编程" style="width: 100%; padding: 8px; border: 1px solid #e0e0e0; border-radius: 5px;">
                                    </div>
                                    
                                    <button onclick="storeMemory()" class="btn btn-primary" style="width: 100%;">💾 存储记忆</button>
                                </div>

                                <!-- 检索记忆 -->
                                <div style="background: white; border-radius: 10px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                                    <h4 style="margin-bottom: 15px; color: #667eea;">🔍 检索记忆</h4>
                                    <input type="text" id="memoryQuery" placeholder="输入查询内容..." style="width: 100%; padding: 8px; border: 1px solid #e0e0e0; border-radius: 5px; margin-bottom: 10px;">
                                    
                                    <div style="display: flex; gap: 10px; margin-bottom: 10px; font-size: 13px;">
                                        <label style="display: flex; align-items: center; gap: 5px; cursor: pointer;">
                                            <input type="checkbox" id="filterSemantic" checked> 语义
                                        </label>
                                        <label style="display: flex; align-items: center; gap: 5px; cursor: pointer;">
                                            <input type="checkbox" id="filterEpisodic" checked> 情景
                                        </label>
                                        <label style="display: flex; align-items: center; gap: 5px; cursor: pointer;">
                                            <input type="checkbox" id="filterLongTerm" checked> 长期
                                        </label>
                                    </div>
                                    
                                    <button onclick="retrieveMemories()" class="btn btn-primary" style="width: 100%;">🔍 搜索记忆</button>
                                </div>

                                <!-- 记忆统计 -->
                                <div style="background: white; border-radius: 10px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                                    <h4 style="margin-bottom: 15px; color: #667eea;">📊 记忆统计</h4>
                                    <div id="memoryStats" style="background: #f8f9fa; padding: 15px; border-radius: 8px; font-size: 13px; line-height: 1.8; min-height: 150px;">
                                        <p>加载中...</p>
                                    </div>
                                    <button onclick="loadMemoryStats()" class="btn btn-secondary" style="width: 100%; margin-top: 10px;">🔄 刷新统计</button>
                                </div>
                            </div>

                            <!-- 右侧：对话和显示区域 -->
                            <div style="display: flex; flex-direction: column; gap: 15px;">
                                <!-- 基于记忆的对话 -->
                                <div style="background: white; border-radius: 10px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                                    <h4 style="margin-bottom: 15px; color: #667eea;">💬 基于记忆的对话</h4>
                                    <div id="memoryMessages" style="height: 300px; overflow-y: auto; border: 1px solid #e0e0e0; border-radius: 8px; padding: 15px; margin-bottom: 15px; background: #f8f9fa;"></div>
                                    <div style="display: flex; gap: 10px;">
                                        <textarea id="memoryChatInput" placeholder="输入消息... (AI会基于存储的记忆回答)" rows="2" style="flex: 1; padding: 10px; border: 2px solid #e0e0e0; border-radius: 5px;"></textarea>
                                        <button onclick="sendMemoryChat()" class="btn btn-primary" style="height: auto;">发送</button>
                                    </div>
                                </div>

                                <!-- 检索结果 -->
                                <div style="background: white; border-radius: 10px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                                    <h4 style="margin-bottom: 15px; color: #667eea;">📋 检索结果</h4>
                                    <div id="memoryResults" style="max-height: 400px; overflow-y: auto;">
                                        <p style="color: #999; text-align: center; padding: 40px 20px;">检索结果将显示在这里...</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 文档详情模态框 -->
    <div id="docModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>📄 文档详情</h3>
                <button class="modal-close" onclick="closeDocModal()">&times;</button>
            </div>
            <div class="modal-body" id="docModalBody">
                <!-- 内容将通过 JavaScript 填充 -->
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeDocModal()">关闭</button>
                <button class="btn btn-danger" onclick="deleteCurrentDoc()" id="deleteDocBtn">删除文档</button>
            </div>
        </div>
    </div>

    <script>
        const API_BASE = window.location.origin;
        let isLoading = false;

        // 配置 marked
        if (typeof marked !== 'undefined') {
            marked.setOptions({
                breaks: true,
                gfm: true
            });
        }

        // 切换标签页
        function switchTab(tabName) {
            // 移除所有active类
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            
            // 添加active类到当前标签
            event.target.classList.add('active');
            document.getElementById(tabName + 'Tab').classList.add('active');
        }

        // 自动调整文本框高度
        function autoResize(textarea) {
            textarea.style.height = 'auto';
            textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
        }

        document.getElementById('userInput').addEventListener('input', function() {
            autoResize(this);
        });

        document.getElementById('ragInput').addEventListener('input', function() {
            autoResize(this);
        });

        // 渲染 Markdown
        function renderMarkdown(content) {
            if (typeof marked === 'undefined' || typeof DOMPurify === 'undefined') {
                return content;
            }
            try {
                const rawHtml = marked.parse(content);
                return DOMPurify.sanitize(rawHtml);
            } catch (error) {
                return content;
            }
        }

        // 添加消息
        function addMessage(containerId, role, content, messageId = null) {
            const container = document.getElementById(containerId);
            
            // 移除空状态
            const emptyState = container.querySelector('.empty-state');
            if (emptyState) {
                emptyState.remove();
            }

            let messageDiv = messageId ? document.getElementById(messageId) : null;
            
            if (messageDiv) {
                // 更新现有消息
                const contentDiv = messageDiv.querySelector('.message-content');
                if (role === 'assistant') {
                    contentDiv.innerHTML = renderMarkdown(content);
                } else {
                    contentDiv.textContent = content;
                }
            } else {
                // 创建新消息
                messageDiv = document.createElement('div');
                messageDiv.className = `message ${role}`;
                if (messageId) {
                    messageDiv.id = messageId;
                }
                
                const contentDiv = document.createElement('div');
                contentDiv.className = 'message-content';
                
                if (role === 'assistant') {
                    contentDiv.innerHTML = renderMarkdown(content);
                } else {
                    contentDiv.textContent = content;
                }
                
                messageDiv.appendChild(contentDiv);
                container.appendChild(messageDiv);
            }
            
            container.scrollTop = container.scrollHeight;
            return messageDiv.id || `msg-${Date.now()}`;
        }

        // 显示加载指示器
        function showTyping(containerId, messageId) {
            const container = document.getElementById(containerId);
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message assistant';
            messageDiv.id = messageId;
            
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.innerHTML = '<div class="typing-indicator"><span></span><span></span><span></span></div>';
            
            messageDiv.appendChild(contentDiv);
            container.appendChild(messageDiv);
            container.scrollTop = container.scrollHeight;
        }

        // 普通对话发送消息
        async function sendMessage() {
            if (isLoading) return;

            const input = document.getElementById('userInput');
            const message = input.value.trim();
            if (!message) return;

            const agentType = document.getElementById('agentType').value;
            const sendBtn = document.getElementById('sendBtn');

            addMessage('chatContainer', 'user', message);
            input.value = '';
            input.style.height = 'auto';

            isLoading = true;
            sendBtn.disabled = true;
            sendBtn.innerHTML = '<span class="loading-spinner"></span>';

            const messageId = `msg-${Date.now()}`;
            showTyping('chatContainer', messageId);

            try {
                const response = await fetch(`${API_BASE}/api/chat/stream`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        message: message,
                        agent_type: agentType,
                        session_id: 'default'
                    })
                });

                if (!response.ok) throw new Error('请求失败');

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let fullResponse = '';

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value, { stream: true });
                    const lines = chunk.split('\n');

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(6));
                                if (data.content) {
                                    fullResponse += data.content;
                                    addMessage('chatContainer', 'assistant', fullResponse, messageId);
                                }
                            } catch (e) {}
                        }
                    }
                }
            } catch (error) {
                console.error('Error:', error);
                const msgElement = document.getElementById(messageId);
                if (msgElement) msgElement.remove();
                addMessage('chatContainer', 'assistant', `错误: ${error.message}`);
            } finally {
                isLoading = false;
                sendBtn.disabled = false;
                sendBtn.textContent = '发送';
            }
        }

        // RAG 查询
        async function sendRagQuery() {
            if (isLoading) return;

            const input = document.getElementById('ragInput');
            const message = input.value.trim();
            if (!message) return;

            const select = document.getElementById('ragCollection');
            const collection = select.value;
            
            // 检查是否选择了知识库
            if (!collection) {
                alert('请先选择一个知识库！');
                return;
            }
            
            const topK = parseInt(document.getElementById('topK').value);
            const optimizeQuery = document.getElementById('optimizeQuery').checked;
            const useHistory = document.getElementById('useHistory').checked;
            const sendBtn = document.getElementById('ragSendBtn');

            addMessage('ragChatContainer', 'user', message);
            input.value = '';
            input.style.height = 'auto';

            isLoading = true;
            sendBtn.disabled = true;
            sendBtn.innerHTML = '<span class="loading-spinner"></span>';

            const messageId = `rag-msg-${Date.now()}`;
            showTyping('ragChatContainer', messageId);

            try {
                const response = await fetch(`${API_BASE}/api/rag/query/stream`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        question: message,
                        collection_name: collection,
                        session_id: 'default',
                        top_k: topK,
                        use_history: useHistory,
                        optimize_query: optimizeQuery
                    })
                });

                if (!response.ok) throw new Error('RAG 查询失败');

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let fullResponse = '';

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value, { stream: true });
                    const lines = chunk.split('\n');

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(6));
                                if (data.content) {
                                    fullResponse += data.content;
                                    addMessage('ragChatContainer', 'assistant', fullResponse, messageId);
                                }
                                if (data.error) {
                                    throw new Error(data.error);
                                }
                            } catch (e) {
                                if (e.message) throw e;
                            }
                        }
                    }
                }
            } catch (error) {
                console.error('Error:', error);
                const msgElement = document.getElementById(messageId);
                if (msgElement) msgElement.remove();
                addMessage('ragChatContainer', 'assistant', `错误: ${error.message}`);
            } finally {
                isLoading = false;
                sendBtn.disabled = false;
                sendBtn.textContent = '发送';
            }
        }

        // 上传文本
        async function uploadTexts() {
            const content = document.getElementById('textContent').value.trim();
            const collection = document.getElementById('uploadCollection').value;
            const resultDiv = document.getElementById('uploadTextResult');

            if (!content) {
                resultDiv.innerHTML = '<div class="alert alert-error">请输入文本内容</div>';
                return;
            }

            const texts = content.split('\n').filter(t => t.trim());
            
            try {
                resultDiv.innerHTML = '<div class="alert alert-info">上传中...</div>';
                
                const response = await fetch(`${API_BASE}/api/rag/upload/texts`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        texts: texts,
                        collection_name: collection
                    })
                });

                const data = await response.json();
                
                if (response.ok) {
                    const actualCollectionName = data.collection_name || collection;
                    const originalName = data.original_name || collection;
                    
                    let successMsg = `✓ 成功上传 ${data.chunks_added} 个文档片段<br>总文档数: ${data.total_documents}<br>`;
                    if (originalName !== actualCollectionName) {
                        successMsg += `<br>💡 <strong>名称映射</strong><br>`;
                        successMsg += `原始名称: <code style="background: rgba(0,0,0,0.1); padding: 2px 6px; border-radius: 3px;">${escapeHtml(originalName)}</code><br>`;
                        successMsg += `编码名称: <code style="background: rgba(0,0,0,0.1); padding: 2px 6px; border-radius: 3px;">${actualCollectionName}</code>`;
                    } else {
                        successMsg += `知识库: <strong>${actualCollectionName}</strong>`;
                    }
                    
                    resultDiv.innerHTML = `<div class="alert alert-success">${successMsg}</div>`;
                    document.getElementById('textContent').value = '';
                    // 同步所有知识库名称输入框（使用实际的集合名称）
                    syncCollectionName(actualCollectionName);
                    // 自动刷新映射表
                    loadMappings();
                } else {
                    resultDiv.innerHTML = `<div class="alert alert-error">✗ ${data.detail}</div>`;
                }
            } catch (error) {
                resultDiv.innerHTML = `<div class="alert alert-error">✗ ${error.message}</div>`;
            }
        }

        // 上传文件
        async function uploadFile() {
            const filePath = document.getElementById('filePath').value.trim();
            const collection = document.getElementById('fileUploadCollection').value;
            const resultDiv = document.getElementById('uploadFileResult');

            if (!filePath) {
                resultDiv.innerHTML = '<div class="alert alert-error">请输入文件路径</div>';
                return;
            }

            try {
                resultDiv.innerHTML = '<div class="alert alert-info">上传中...</div>';
                
                const response = await fetch(`${API_BASE}/api/rag/upload/file`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        file_path: filePath,
                        collection_name: collection
                    })
                });

                const data = await response.json();
                
                if (response.ok) {
                    const actualCollectionName = data.collection_name || collection;
                    const originalName = data.original_name || collection;
                    
                    let successMsg = `✓ 成功上传 ${data.chunks_added} 个文档片段<br>总文档数: ${data.total_documents}<br>`;
                    if (originalName !== actualCollectionName) {
                        successMsg += `<br>💡 <strong>名称映射</strong><br>`;
                        successMsg += `原始名称: <code style="background: rgba(0,0,0,0.1); padding: 2px 6px; border-radius: 3px;">${escapeHtml(originalName)}</code><br>`;
                        successMsg += `编码名称: <code style="background: rgba(0,0,0,0.1); padding: 2px 6px; border-radius: 3px;">${actualCollectionName}</code>`;
                    } else {
                        successMsg += `知识库: <strong>${actualCollectionName}</strong>`;
                    }
                    
                    resultDiv.innerHTML = `<div class="alert alert-success">${successMsg}</div>`;
                    document.getElementById('filePath').value = '';
                    // 同步所有知识库名称输入框（使用实际的集合名称）
                    syncCollectionName(actualCollectionName);
                    // 自动刷新映射表
                    loadMappings();
                } else {
                    resultDiv.innerHTML = `<div class="alert alert-error">✗ ${data.detail}</div>`;
                }
            } catch (error) {
                resultDiv.innerHTML = `<div class="alert alert-error">✗ ${error.message}</div>`;
            }
        }

        // 获取知识库信息
        async function getKnowledgeInfo() {
            const select = document.getElementById('infoCollection');
            const collection = select.value;
            const infoDiv = document.getElementById('knowledgeInfo');
            
            if (!collection) {
                infoDiv.innerHTML = '<div class="alert alert-error">请先选择一个知识库</div>';
                return;
            }

            try {
                infoDiv.innerHTML = '<div class="alert alert-info">加载中...</div>';
                
                const response = await fetch(`${API_BASE}/api/rag/info/${collection}`);
                const data = await response.json();
                
                if (response.ok) {
                    let mappingHtml = '';
                    if (data.is_normalized && data.original_name) {
                        mappingHtml = `
                            <div class="alert alert-info" style="margin-top: 12px; font-size: 13px;">
                                💡 <strong>名称映射</strong><br>
                                原始名称: <code style="background: rgba(0,0,0,0.1); padding: 2px 6px; border-radius: 3px;">${escapeHtml(data.original_name)}</code><br>
                                编码名称: <code style="background: rgba(0,0,0,0.1); padding: 2px 6px; border-radius: 3px;">${data.collection_name}</code>
                            </div>
                        `;
                    }
                    
                    infoDiv.innerHTML = `
                        <div class="info-item">
                            <span class="info-label">集合名称：</span>
                            <span class="info-value">${data.collection_name}</span>
                        </div>
                        ${data.original_name ? `
                        <div class="info-item">
                            <span class="info-label">原始名称：</span>
                            <span class="info-value" style="color: #10b981;">${escapeHtml(data.original_name)}</span>
                        </div>
                        ` : ''}
                        <div class="info-item">
                            <span class="info-label">文档数量：</span>
                            <span class="info-value">${data.document_count}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">检索模式：</span>
                            <span class="info-value">${data.retrieval_mode}</span>
                        </div>
                        ${mappingHtml}
                    `;
                } else {
                    infoDiv.innerHTML = `<div class="alert alert-error">✗ ${data.detail}</div>`;
                }
            } catch (error) {
                infoDiv.innerHTML = `<div class="alert alert-error">✗ ${error.message}</div>`;
            }
        }

        // 加载名称映射关系
        async function loadMappings() {
            const mappingsDiv = document.getElementById('mappingsList');
            
            try {
                mappingsDiv.innerHTML = '<div class="alert alert-info">加载中...</div>';
                
                const response = await fetch(`${API_BASE}/api/rag/mappings`);
                const data = await response.json();
                
                if (response.ok) {
                    if (data.mappings.length === 0) {
                        mappingsDiv.innerHTML = '<div class="alert alert-info">暂无映射关系</div>';
                        return;
                    }
                    
                    let html = `
                        <div style="font-size: 12px; color: #6c757d; margin-bottom: 8px;">
                            共 ${data.total_count} 个映射
                        </div>
                        <div style="max-height: 300px; overflow-y: auto; border: 2px solid #e9ecef; border-radius: 8px;">
                    `;
                    
                    data.mappings.forEach((mapping, index) => {
                        const docCountText = mapping.document_count !== null ? `${mapping.document_count} 个文档` : '未加载';
                        html += `
                            <div style="padding: 12px; border-bottom: 1px solid #e9ecef; ${index % 2 === 0 ? 'background: #f8f9fa;' : ''}">
                                <div style="display: flex; justify-content: space-between; align-items: flex-start; gap: 10px;">
                                    <div style="flex: 1; min-width: 0;">
                                        <div style="font-size: 12px; color: #10b981; font-weight: 600; margin-bottom: 4px;">
                                            📝 ${escapeHtml(mapping.original_name)}
                                        </div>
                                        <div style="font-size: 11px; color: #6c757d; font-family: 'Courier New', monospace; word-break: break-all;">
                                            ➜ ${mapping.normalized_name}
                                        </div>
                                    </div>
                                    <div style="font-size: 11px; color: #667eea; white-space: nowrap;">
                                        ${docCountText}
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                    
                    html += '</div>';
                    mappingsDiv.innerHTML = html;
                } else {
                    mappingsDiv.innerHTML = `<div class="alert alert-error">✗ ${data.detail}</div>`;
                }
            } catch (error) {
                mappingsDiv.innerHTML = `<div class="alert alert-error">✗ ${error.message}</div>`;
            }
        }

        // 清空知识库
        async function clearKnowledgeBase() {
            const collection = document.getElementById('manageCollection').value;
            
            if (!confirm(`确定要清空知识库"${collection}"吗？此操作不可恢复！`)) {
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/api/rag/clear/${collection}`, {
                    method: 'DELETE'
                });

                const data = await response.json();
                
                if (response.ok) {
                    alert('✓ 知识库已清空');
                    getKnowledgeInfo();
                } else {
                    alert(`✗ 清空失败: ${data.detail}`);
                }
            } catch (error) {
                alert(`✗ 清空失败: ${error.message}`);
            }
        }

        // 清除对话历史
        async function clearChatHistory() {
            if (!confirm('确定要清除对话历史吗？')) return;

            try {
                await fetch(`${API_BASE}/api/history/default`, { method: 'DELETE' });
                const container = document.getElementById('chatContainer');
                container.innerHTML = `
                    <div class="empty-state">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
                        </svg>
                        <h3>开始对话</h3>
                        <p>选择 Agent 类型，然后输入您的问题开始对话</p>
                    </div>
                `;
            } catch (error) {
                alert('清除失败: ' + error.message);
            }
        }

        // 清除 RAG 历史
        async function clearRagHistory() {
            if (!confirm('确定要清除 RAG 对话历史吗？')) return;

            const select = document.getElementById('ragCollection');
            const collection = select.value;
            
            if (!collection) {
                alert('请先选择一个知识库！');
                return;
            }
            
            try {
                await fetch(`${API_BASE}/api/rag/history/${collection}/default`, { method: 'DELETE' });
                const container = document.getElementById('ragChatContainer');
                container.innerHTML = `
                    <div class="empty-state">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
                        </svg>
                        <h3>RAG 问答</h3>
                        <p>基于知识库的智能问答，支持多种检索模式</p>
                    </div>
                `;
            } catch (error) {
                alert('清除失败: ' + error.message);
            }
        }

        // 回车发送
        document.getElementById('userInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        document.getElementById('ragInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendRagQuery();
            }
        });

        // 同步所有知识库名称输入框
        function syncCollectionName(collectionName) {
            // 更新所有知识库相关的输入框
            document.getElementById('uploadCollection').value = collectionName;
            document.getElementById('fileUploadCollection').value = collectionName;
            document.getElementById('infoCollection').value = collectionName;
            document.getElementById('manageCollection').value = collectionName;
            document.getElementById('browserCollection').value = collectionName;
            document.getElementById('ragCollection').value = collectionName;
            
            console.log(`已同步知识库名称: ${collectionName}`);
        }

        // 文档浏览器功能
        let currentDocId = null;
        let currentCollection = null;
        let selectedDocIds = new Set();

        // 加载文档列表
        async function loadDocuments(limit = 50) {
            const select = document.getElementById('browserCollection');
            const collection = select.value;
            const browserDiv = document.getElementById('docBrowser');
            const statsDiv = document.getElementById('docStats');
            
            if (!collection) {
                browserDiv.innerHTML = '<div class="alert alert-error">请先选择一个知识库</div>';
                return;
            }

            try {
                browserDiv.innerHTML = '<div class="alert alert-info">加载中...</div>';
                statsDiv.innerHTML = '';

                const response = await fetch(`${API_BASE}/api/rag/documents/${collection}?limit=${limit}`);
                const data = await response.json();

                if (!response.ok) {
                    browserDiv.innerHTML = `<div class="alert alert-error">✗ ${data.detail}</div>`;
                    return;
                }

                // 显示统计信息
                statsDiv.innerHTML = `
                    <div class="doc-stats">
                        <div class="doc-stat-item">
                            <span class="doc-stat-label">知识库：</span>
                            <span class="doc-stat-value">${data.collection_name}</span>
                        </div>
                        <div class="doc-stat-item">
                            <span class="doc-stat-label">总文档数：</span>
                            <span class="doc-stat-value">${data.total_count}</span>
                        </div>
                        <div class="doc-stat-item">
                            <span class="doc-stat-label">显示：</span>
                            <span class="doc-stat-value">${data.count} / ${data.total_count}</span>
                        </div>
                    </div>
                `;

                if (data.documents.length === 0) {
                    browserDiv.innerHTML = '<div class="alert alert-info">该知识库暂无文档</div>';
                    return;
                }

                // 渲染文档列表
                let html = '<div class="doc-browser scrollbar">';
                data.documents.forEach(doc => {
                    const shortText = doc.text.length > 100 ? doc.text.substring(0, 100) + '...' : doc.text;
                    html += `
                        <div class="doc-item">
                            <input type="checkbox" class="doc-checkbox" data-doc-id="${escapeAttr(doc.id)}" onchange="toggleDocSelection('${escapeAttr(doc.id)}', this.checked)">
                            <div class="doc-content" style="flex: 1;">
                                <div class="doc-id">ID: ${doc.id}</div>
                                <div class="doc-text">${escapeHtml(shortText)}</div>
                            </div>
                            <div class="doc-actions">
                                <button class="btn btn-sm btn-view" onclick="viewDocument('${escapeAttr(collection)}', '${escapeAttr(doc.id)}')">查看</button>
                                <button class="btn btn-sm btn-delete" onclick="deleteDocumentById('${escapeAttr(collection)}', '${escapeAttr(doc.id)}')">删除</button>
                            </div>
                        </div>
                    `;
                });
                html += '</div>';
                browserDiv.innerHTML = html;
                
                // 重置选择
                selectedDocIds.clear();
                updateBatchDeleteButton();

            } catch (error) {
                browserDiv.innerHTML = `<div class="alert alert-error">✗ ${error.message}</div>`;
            }
        }

        // 刷新文档列表
        function refreshDocuments() {
            loadDocuments();
        }

        // 查看文档详情
        async function viewDocument(collection, docId) {
            currentCollection = collection;
            currentDocId = docId;

            const modal = document.getElementById('docModal');
            const modalBody = document.getElementById('docModalBody');

            try {
                modalBody.innerHTML = '<div class="alert alert-info">加载中...</div>';
                modal.classList.add('active');

                const response = await fetch(`${API_BASE}/api/rag/document/${collection}/${docId}`);
                const data = await response.json();

                if (!response.ok) {
                    modalBody.innerHTML = `<div class="alert alert-error">✗ ${data.detail}</div>`;
                    return;
                }

                const doc = data.document;
                modalBody.innerHTML = `
                    <div class="doc-id">ID: ${doc.id}</div>
                    <div class="doc-text">${escapeHtml(doc.text)}</div>
                    ${doc.metadata && Object.keys(doc.metadata).length > 0 ? `
                        <div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid #e9ecef;">
                            <strong style="font-size: 13px; color: #6c757d;">元数据：</strong>
                            <pre style="margin-top: 8px; background: #f8f9fa; padding: 10px; border-radius: 6px; font-size: 12px;">${JSON.stringify(doc.metadata, null, 2)}</pre>
                        </div>
                    ` : ''}
                `;

            } catch (error) {
                modalBody.innerHTML = `<div class="alert alert-error">✗ ${error.message}</div>`;
            }
        }

        // 关闭模态框
        function closeDocModal() {
            const modal = document.getElementById('docModal');
            modal.classList.remove('active');
            currentDocId = null;
            currentCollection = null;
        }

        // 点击模态框背景关闭
        document.getElementById('docModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeDocModal();
            }
        });

        // 删除当前查看的文档
        async function deleteCurrentDoc() {
            if (!currentDocId || !currentCollection) return;

            if (!confirm('确定要删除这个文档吗？此操作不可恢复！')) {
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/api/rag/document/${currentCollection}/${currentDocId}`, {
                    method: 'DELETE'
                });

                const data = await response.json();

                if (response.ok) {
                    alert('✓ 文档已删除');
                    closeDocModal();
                    // 刷新文档列表
                    if (document.getElementById('browserCollection').value === currentCollection) {
                        loadDocuments();
                    }
                } else {
                    alert(`✗ 删除失败: ${data.detail}`);
                }
            } catch (error) {
                alert(`✗ 删除失败: ${error.message}`);
            }
        }

        // 直接删除文档（从列表）
        async function deleteDocumentById(collection, docId) {
            if (!confirm('确定要删除这个文档吗？此操作不可恢复！')) {
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/api/rag/document/${collection}/${docId}`, {
                    method: 'DELETE'
                });

                const data = await response.json();

                if (response.ok) {
                    alert('✓ 文档已删除');
                    // 刷新文档列表
                    loadDocuments();
                } else {
                    alert(`✗ 删除失败: ${data.detail}`);
                }
            } catch (error) {
                alert(`✗ 删除失败: ${error.message}`);
            }
        }

        // HTML 转义函数
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 属性转义函数
        function escapeAttr(text) {
            return text.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
        }

        // 加载所有collection列表
        async function loadAllCollections() {
            const listDiv = document.getElementById('collectionsList');
            
            try {
                console.log('[loadAllCollections] 开始加载...');
                console.log('[loadAllCollections] listDiv:', listDiv);
                
                listDiv.innerHTML = '<div class="alert alert-info">加载中...</div>';
                
                console.log('[loadAllCollections] 正在获取collections列表...');
                const response = await fetch(`${API_BASE}/api/rag/collections`);
                
                console.log('响应状态:', response.status);
                
                // 先解析JSON
                let data;
                try {
                    data = await response.json();
                } catch (parseError) {
                    throw new Error(`JSON解析失败: ${parseError.message}`);
                }
                
                if (response.ok) {
                    console.log('成功获取collections:', data);
                    
                    if (data.collections.length === 0) {
                        listDiv.innerHTML = '<div class="alert alert-info">暂无知识库（data/chroma目录为空）</div>';
                        return;
                    }
                    
                    let html = `
                        <div style="font-size: 12px; color: #6c757d; margin-bottom: 8px;">
                            共 ${data.total_count} 个知识库
                        </div>
                        <div style="max-height: 300px; overflow-y: auto; border: 2px solid #e9ecef; border-radius: 8px;">
                    `;
                    
                    data.collections.forEach((coll, index) => {
                        // 优先显示原始名称，如果有的话
                        const displayName = coll.original_name || coll.collection_name;
                        console.log(`Collection ${index}:`, coll.collection_name, '→', displayName, 'is_normalized:', coll.is_normalized);
                        html += `
                            <div style="padding: 12px; border-bottom: 1px solid #e9ecef; ${index % 2 === 0 ? 'background: #f8f9fa;' : ''}" onclick="selectCollection('${escapeAttr(coll.collection_name)}');" style="cursor: pointer;">
                                <div style="display: flex; justify-content: space-between; align-items: flex-start; gap: 10px;">
                                    <div style="flex: 1; min-width: 0;">
                                        <div style="font-size: 13px; color: #667eea; font-weight: 600; margin-bottom: 4px;">
                                            📚 ${escapeHtml(displayName)}
                                        </div>
                                        ${coll.is_normalized ? `
                                            <div style="font-size: 11px; color: #6c757d; font-family: 'Courier New', monospace; word-break: break-all;">
                                                编码: ${coll.collection_name}
                                            </div>
                                        ` : ''}
                                    </div>
                                    <div style="font-size: 11px; color: #10b981; white-space: nowrap; font-weight: 600;">
                                        ${coll.document_count} 个文档
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                    
                    html += '</div>';
                    listDiv.innerHTML = html;
                    
                    // 同时更新下拉选择框
                    updateCollectionSelects(data.collections);
                } else {
                    console.error('获取collections失败:', data);
                    const errorMsg = data.detail || data.message || '未知错误';
                    listDiv.innerHTML = `<div class="alert alert-error">✗ ${errorMsg}<br><small>状态码: ${response.status}</small></div>`;
                }
            } catch (error) {
                console.error('加载collections异常:', error);
                listDiv.innerHTML = `<div class="alert alert-error">✗ ${error.message}<br><small>请检查服务器是否正常运行</small></div>`;
            }
        }

        // 更新所有下拉选择框
        function updateCollectionSelects(collections) {
            const selects = [
                document.getElementById('ragCollection'),
                document.getElementById('infoCollection'),
                document.getElementById('browserCollection')
            ];
            
            selects.forEach(select => {
                if (!select) return;
                
                // 保存当前选中的值
                const currentValue = select.value;
                
                // 清空并重新填充选项
                select.innerHTML = '<option value="">-- 请选择知识库 --</option>';
                
                collections.forEach(coll => {
                    const displayName = coll.original_name || coll.collection_name;
                    const option = document.createElement('option');
                    option.value = coll.collection_name;
                    option.textContent = `${displayName} (${coll.document_count}个文档)`;
                    select.appendChild(option);
                });
                
                // 恢复之前的选择
                if (currentValue && collections.find(c => c.collection_name === currentValue)) {
                    select.value = currentValue;
                }
            });
            
            console.log(`已更新 ${selects.length} 个下拉选择框`);
        }
        
        // 选择collection并同步到所有输入框
        function selectCollection(collectionName) {
            syncCollectionName(collectionName);
            
            // 同时更新下拉选择框的值
            const ragSelect = document.getElementById('ragCollection');
            const infoSelect = document.getElementById('infoCollection');
            const browserSelect = document.getElementById('browserCollection');
            
            if (ragSelect) ragSelect.value = collectionName;
            if (infoSelect) infoSelect.value = collectionName;
            if (browserSelect) browserSelect.value = collectionName;
            
            alert(`已选择知识库: ${collectionName}\n所有知识库输入框已同步更新`);
        }

        // 切换文档选择
        function toggleDocSelection(docId, checked) {
            if (checked) {
                selectedDocIds.add(docId);
            } else {
                selectedDocIds.delete(docId);
            }
            updateBatchDeleteButton();
        }

        // 更新批量删除按钮显示
        function updateBatchDeleteButton() {
            const btn = document.getElementById('batchDeleteBtn');
            if (selectedDocIds.size > 0) {
                btn.style.display = 'inline-block';
                btn.textContent = `删除选中 (${selectedDocIds.size})`;
            } else {
                btn.style.display = 'none';
            }
        }

        // 批量删除文档
        async function batchDeleteDocuments() {
            if (selectedDocIds.size === 0) {
                alert('请先选择要删除的文档');
                return;
            }

            const collection = document.getElementById('browserCollection').value;
            
            if (!confirm(`确定要删除选中的 ${selectedDocIds.size} 个文档吗？此操作不可恢复！`)) {
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/api/rag/documents/batch`, {
                    method: 'DELETE',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        collection_name: collection,
                        doc_ids: Array.from(selectedDocIds)
                    })
                });

                const data = await response.json();

                if (response.ok) {
                    alert(`✓ 批量删除完成\n成功: ${data.success_count}\n失败: ${data.failed_count}\n剩余文档: ${data.remaining_count}`);
                    // 刷新文档列表
                    loadDocuments();
                } else {
                    alert(`✗ 批量删除失败: ${data.detail}`);
                }
            } catch (error) {
                alert(`✗ 批量删除失败: ${error.message}`);
            }
        }

        // 页面加载时检查健康状态并加载collection列表
        window.addEventListener('load', async () => {
            try {
                const response = await fetch(`${API_BASE}/api/health`);
                const data = await response.json();
                console.log('Health check:', data);
                
                // 自动加载collection列表
                loadAllCollections();
                
                // 加载提示链类型
                loadChainTypes();
                
                // 加载路由场景
                loadRoutingScenarios();
            } catch (error) {
                console.error('Health check failed:', error);
            }
        });

        // ==================== Prompt Chaining 相关函数 ====================

        let chainTypes = {};
        let currentChainResult = null;

        // 加载可用的提示链类型
        async function loadChainTypes() {
            try {
                const response = await fetch(`${API_BASE}/api/prompt-chaining/types`);
                const data = await response.json();
                chainTypes = {};
                data.chain_types.forEach(type => {
                    chainTypes[type.id] = type;
                });
                console.log('已加载提示链类型:', chainTypes);
            } catch (error) {
                console.error('加载提示链类型失败:', error);
            }
        }

        // 更新场景信息
        function updateChainInfo() {
            const chainType = document.getElementById('chainType').value;
            const infoDiv = document.getElementById('chainInfo');
            const inputTextarea = document.getElementById('chainInput');
            const runBtn = document.getElementById('runChainBtn');
            
            if (!chainType) {
                infoDiv.style.display = 'none';
                inputTextarea.placeholder = '请先选择一个场景...';
                runBtn.disabled = true;
                return;
            }
            
            const typeInfo = chainTypes[chainType];
            if (!typeInfo) return;
            
            // 显示场景信息
            infoDiv.style.display = 'block';
            document.getElementById('chainDescription').textContent = typeInfo.description;
            
            // 显示步骤
            const stepsHtml = `
                <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                    ${typeInfo.steps.map((step, idx) => `
                        <div style="background: white; padding: 8px 12px; border-radius: 6px; border: 1px solid #dee2e6; font-size: 13px;">
                            ${idx + 1}. ${step}
                        </div>
                    `).join(' → ')}
                </div>
            `;
            document.getElementById('chainSteps').innerHTML = stepsHtml;
            document.getElementById('chainHint').innerHTML = `💡 ${typeInfo.input_hint}`;
            
            // 更新输入框提示
            inputTextarea.placeholder = typeInfo.input_hint;
            runBtn.disabled = false;
        }

        // 运行提示链
        async function runPromptChain() {
            const chainType = document.getElementById('chainType').value;
            const inputText = document.getElementById('chainInput').value.trim();
            const runBtn = document.getElementById('runChainBtn');
            const resultCard = document.getElementById('chainResultCard');
            const progressDiv = document.getElementById('chainProgress');
            const stepsDetailsDiv = document.getElementById('chainStepsDetails');
            
            if (!chainType) {
                alert('请先选择一个场景');
                return;
            }
            
            if (!inputText) {
                alert('请输入内容');
                return;
            }
            
            // 显示结果卡片和进度
            resultCard.style.display = 'block';
            progressDiv.style.display = 'block';
            stepsDetailsDiv.innerHTML = '';
            document.getElementById('finalOutputContent').innerHTML = '';
            document.getElementById('chainMetadata').innerHTML = '';
            
            // 禁用按钮
            runBtn.disabled = true;
            runBtn.innerHTML = '<span>⏳ 执行中...</span>';
            
            const typeInfo = chainTypes[chainType];
            const totalSteps = typeInfo.steps.length;
            let currentStepNum = 0;
            let intermediateResults = [];
            
            try {
                // 使用流式 API
                const response = await fetch(`${API_BASE}/api/prompt-chaining/run/stream`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        input_text: inputText,
                        chain_type: chainType,
                        save_result: true
                    })
                });
                
                if (!response.ok) {
                    throw new Error('请求失败');
                }
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                let currentStepContent = '';
                
                while (true) {
                    const { done, value } = await reader.read();
                    
                    if (done) break;
                    
                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n');
                    buffer = lines.pop() || '';
                    
                    for (const line of lines) {
                        if (!line.trim() || !line.startsWith('data: ')) continue;
                        
                        try {
                            const data = JSON.parse(line.slice(6));
                            
                            if (data.error) {
                                throw new Error(data.error);
                            }
                            
                            if (data.type === 'info') {
                                // 初始化信息
                                document.getElementById('currentStep').textContent = '准备执行...';
                                document.getElementById('stepCounter').textContent = `0 / ${data.total_steps}`;
                            } else if (data.type === 'step_start') {
                                // 步骤开始
                                currentStepNum = data.step;
                                currentStepContent = '';
                                
                                document.getElementById('currentStep').textContent = `步骤 ${data.step}: ${data.name}`;
                                document.getElementById('stepCounter').textContent = `${data.step} / ${totalSteps}`;
                                document.getElementById('progressBar').style.width = `${(data.step - 1) / totalSteps * 100}%`;
                                
                                // 添加步骤卡片
                                const stepCard = document.createElement('div');
                                stepCard.id = `step-${data.step}`;
                                stepCard.style.cssText = 'background: #f8f9fa; padding: 16px; border-radius: 8px; margin-bottom: 12px; border: 2px solid #dee2e6;';
                                stepCard.innerHTML = `
                                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                                        <h4 style="margin: 0; color: #495057;">步骤 ${data.step}: ${data.name}</h4>
                                        <span style="font-size: 12px; color: #6c757d;">⏳ 执行中...</span>
                                    </div>
                                    <div style="font-size: 13px; color: #6c757d; margin-bottom: 12px;">${data.description}</div>
                                    <div class="markdown-content" id="step-content-${data.step}" style="background: white; padding: 12px; border-radius: 6px; min-height: 50px;"></div>
                                `;
                                stepsDetailsDiv.appendChild(stepCard);
                                stepCard.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                            } else if (data.type === 'content') {
                                // 流式内容
                                currentStepContent += data.content;
                                const contentDiv = document.getElementById(`step-content-${data.step}`);
                                if (contentDiv) {
                                    contentDiv.textContent = currentStepContent;
                                }
                            } else if (data.type === 'step_complete') {
                                // 步骤完成
                                const stepCard = document.getElementById(`step-${data.step}`);
                                if (stepCard) {
                                    const statusSpan = stepCard.querySelector('span');
                                    if (statusSpan) {
                                        statusSpan.textContent = '✅ 完成';
                                        statusSpan.style.color = '#28a745';
                                    }
                                    stepCard.style.borderColor = '#28a745';
                                }
                                
                                // 渲染 Markdown
                                const contentDiv = document.getElementById(`step-content-${data.step}`);
                                if (contentDiv && typeof marked !== 'undefined') {
                                    const html = marked.parse(data.output);
                                    contentDiv.innerHTML = DOMPurify.sanitize(html);
                                }
                                
                                intermediateResults.push({
                                    step: data.step,
                                    output: data.output
                                });
                                
                                document.getElementById('progressBar').style.width = `${data.step / totalSteps * 100}%`;
                            } else if (data.type === 'done') {
                                // 全部完成
                                document.getElementById('currentStep').textContent = '✅ 执行完成';
                                document.getElementById('stepCounter').textContent = `${totalSteps} / ${totalSteps}`;
                                document.getElementById('progressBar').style.width = '100%';
                                
                                // 显示最终输出
                                const finalContent = document.getElementById('finalOutputContent');
                                if (typeof marked !== 'undefined') {
                                    const html = marked.parse(data.final_output);
                                    finalContent.innerHTML = DOMPurify.sanitize(html);
                                } else {
                                    finalContent.textContent = data.final_output;
                                }
                                
                                // 显示元数据
                                const metadata = document.getElementById('chainMetadata');
                                metadata.innerHTML = `
                                    <div style="display: flex; gap: 20px; flex-wrap: wrap;">
                                        <div>✅ 状态: <strong>成功</strong></div>
                                        <div>📝 总步骤: <strong>${totalSteps}</strong></div>
                                        ${data.output_file ? `<div>💾 已保存: <strong>${data.output_file}</strong></div>` : ''}
                                    </div>
                                `;
                                
                                // 保存结果
                                currentChainResult = {
                                    chain_type: chainType,
                                    chain_name: typeInfo.name,
                                    final_output: data.final_output,
                                    intermediate_results: intermediateResults,
                                    output_file: data.output_file
                                };
                                
                                // 滚动到最终输出
                                document.getElementById('chainFinalOutput').scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                            }
                        } catch (e) {
                            console.error('解析SSE数据失败:', e);
                        }
                    }
                }
                
            } catch (error) {
                console.error('执行失败:', error);
                alert('执行失败: ' + error.message);
                
                const metadata = document.getElementById('chainMetadata');
                metadata.innerHTML = `
                    <div style="color: #dc3545;">
                        ❌ 执行失败: ${error.message}
                    </div>
                `;
            } finally {
                // 恢复按钮
                runBtn.disabled = false;
                runBtn.innerHTML = '<span>▶️ 运行提示链</span>';
            }
        }

        // 清除结果
        function clearChainResult() {
            document.getElementById('chainResultCard').style.display = 'none';
            document.getElementById('chainStepsDetails').innerHTML = '';
            document.getElementById('finalOutputContent').innerHTML = '';
            document.getElementById('chainMetadata').innerHTML = '';
            document.getElementById('chainProgress').style.display = 'none';
            currentChainResult = null;
        }

        // 复制结果
        function copyChainResult() {
            if (!currentChainResult) {
                alert('没有可复制的结果');
                return;
            }
            
            navigator.clipboard.writeText(currentChainResult.final_output)
                .then(() => {
                    alert('✅ 结果已复制到剪贴板');
                })
                .catch(err => {
                    console.error('复制失败:', err);
                    alert('复制失败，请手动复制');
                });
        }

        // 下载结果
        function downloadChainResult() {
            if (!currentChainResult) {
                alert('没有可下载的结果');
                return;
            }
            
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
            const filename = `prompt_chain_${currentChainResult.chain_type}_${timestamp}.md`;
            
            let content = `# ${currentChainResult.chain_name}结果\n\n`;
            content += `**生成时间:** ${new Date().toLocaleString('zh-CN')}\n\n`;
            content += `---\n\n`;
            content += currentChainResult.final_output;
            
            const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            console.log('已下载结果到:', filename);
        }

        // ==================== Routing Agent 相关函数 ====================

        let routingScenarios = [];
        let routingStrategies = [];
        let currentRoutingResult = null;

        // 加载路由场景
        async function loadRoutingScenarios() {
            try {
                const response = await fetch(`${API_BASE}/api/routing/scenarios`);
                const data = await response.json();
                
                routingScenarios = data.scenarios;
                routingStrategies = data.strategies;
                
                // 填充场景下拉框
                const select = document.getElementById('routingScenario');
                select.innerHTML = '<option value="">-- 请选择场景 --</option>';
                data.scenarios.forEach(scenario => {
                    const option = document.createElement('option');
                    option.value = scenario.id;
                    option.textContent = scenario.name;
                    select.appendChild(option);
                });
                
                console.log('已加载路由场景:', routingScenarios);
                
                // 更新策略说明
                updateStrategyDescription();
                
            } catch (error) {
                console.error('加载路由场景失败:', error);
            }
        }

        // 更新策略说明
        function updateStrategyDescription() {
            const strategySelect = document.getElementById('routingStrategy');
            const strategyId = strategySelect.value;
            const descSpan = document.getElementById('strategyDescription');
            
            const strategy = routingStrategies.find(s => s.id === strategyId);
            if (strategy) {
                descSpan.textContent = strategy.description;
            }
        }

        // 监听策略变化
        document.getElementById('routingStrategy').addEventListener('change', updateStrategyDescription);

        // 加载路由列表
        async function loadRoutingRoutes() {
            const select = document.getElementById('routingScenario');
            const scenarioId = select.value;
            const infoDiv = document.getElementById('routingScenarioInfo');
            const routesListDiv = document.getElementById('availableRoutes');
            
            if (!scenarioId) {
                infoDiv.style.display = 'none';
                routesListDiv.innerHTML = '<div class="alert alert-info">请先选择一个场景</div>';
                return;
            }
            
            try {
                // 显示场景信息
                const scenario = routingScenarios.find(s => s.id === scenarioId);
                if (scenario) {
                    infoDiv.style.display = 'block';
                    document.getElementById('routingDescription').textContent = scenario.description;
                    document.getElementById('routingRoutesList').innerHTML = `
                        <strong style="font-size: 13px; color: #495057;">包含路由：</strong>
                        <div style="display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px;">
                            ${scenario.routes.map(route => `
                                <span style="background: white; padding: 6px 12px; border-radius: 6px; border: 1px solid #dee2e6; font-size: 12px;">
                                    ${route}
                                </span>
                            `).join('')}
                        </div>
                    `;
                }
                
                // 加载详细路由信息
                routesListDiv.innerHTML = '<div class="alert alert-info">加载中...</div>';
                
                const response = await fetch(`${API_BASE}/api/routing/routes?scenario=${scenarioId}`);
                const data = await response.json();
                
                if (data.routes.length === 0) {
                    routesListDiv.innerHTML = '<div class="alert alert-info">该场景暂无路由</div>';
                    return;
                }
                
                // 渲染路由列表
                let html = '<div style="display: grid; gap: 12px;">';
                data.routes.forEach(route => {
                    html += `
                        <div style="background: #f8f9fa; padding: 16px; border-radius: 8px; border: 2px solid #dee2e6;">
                            <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px;">
                                <h4 style="margin: 0; color: #667eea; font-size: 15px;">${route.name}</h4>
                                <span style="background: #667eea; color: white; padding: 4px 8px; border-radius: 4px; font-size: 11px;">
                                    优先级: ${route.priority}
                                </span>
                            </div>
                            <p style="margin: 8px 0; color: #6c757d; font-size: 13px;">${route.description}</p>
                            ${route.keywords && route.keywords.length > 0 ? `
                                <div style="margin-top: 8px;">
                                    <strong style="font-size: 12px; color: #495057;">关键词：</strong>
                                    <div style="display: flex; gap: 4px; flex-wrap: wrap; margin-top: 4px;">
                                        ${route.keywords.map(kw => `
                                            <span style="background: #e7f5ff; color: #1e40af; padding: 2px 6px; border-radius: 3px; font-size: 11px;">
                                                ${kw}
                                            </span>
                                        `).join('')}
                                    </div>
                                </div>
                            ` : ''}
                            ${route.examples && route.examples.length > 0 ? `
                                <div style="margin-top: 8px;">
                                    <strong style="font-size: 12px; color: #495057;">示例：</strong>
                                    <ul style="margin: 4px 0 0 20px; font-size: 12px; color: #6c757d;">
                                        ${route.examples.map(ex => `<li>${ex}</li>`).join('')}
                                    </ul>
                                </div>
                            ` : ''}
                        </div>
                    `;
                });
                html += '</div>';
                routesListDiv.innerHTML = html;
                
            } catch (error) {
                console.error('加载路由失败:', error);
                routesListDiv.innerHTML = '<div class="alert alert-error">✗ 加载失败: ' + error.message + '</div>';
            }
        }

        // 执行路由
        async function executeRouting() {
            const inputText = document.getElementById('routingInput').value.trim();
            const scenario = document.getElementById('routingScenario').value;
            const strategy = document.getElementById('routingStrategy').value;
            const executeBtn = document.getElementById('routingExecuteBtn');
            const resultCard = document.getElementById('routingResultCard');
            
            if (!scenario) {
                alert('请先选择一个场景');
                return;
            }
            
            if (!inputText) {
                alert('请输入任务');
                return;
            }
            
            // 显示结果卡片
            resultCard.style.display = 'block';
            
            // 禁用按钮
            executeBtn.disabled = true;
            executeBtn.innerHTML = '<span>⏳ 执行中...</span>';
            
            try {
                const response = await fetch(`${API_BASE}/api/routing/route`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        input_text: inputText,
                        scenario: scenario,
                        strategy: strategy,
                        verbose: false
                    })
                });
                
                const data = await response.json();
                
                if (!response.ok || !data.success) {
                    throw new Error(data.detail || '路由执行失败');
                }
                
                // 显示路由决策
                document.getElementById('selectedRoute').textContent = data.route_description;
                document.getElementById('routingConfidence').textContent = (data.confidence * 100).toFixed(1) + '%';
                document.getElementById('routingTime').textContent = data.execution_time.toFixed(2) + 's';
                document.getElementById('routingReason').textContent = data.routing_reason;
                
                // 更新置信度条
                const confidencePercent = (data.confidence * 100).toFixed(0) + '%';
                document.getElementById('confidencePercent').textContent = confidencePercent;
                document.getElementById('confidenceBar').style.width = confidencePercent;
                
                // 显示处理结果
                const outputDiv = document.getElementById('routingOutput');
                if (typeof marked !== 'undefined') {
                    const html = marked.parse(data.output);
                    outputDiv.innerHTML = DOMPurify.sanitize(html);
                } else {
                    outputDiv.textContent = data.output;
                }
                
                // 保存结果
                currentRoutingResult = data;
                
                // 滚动到结果
                resultCard.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                
            } catch (error) {
                console.error('执行路由失败:', error);
                alert('执行失败: ' + error.message);
            } finally {
                // 恢复按钮
                executeBtn.disabled = false;
                executeBtn.innerHTML = '<span>🚀 执行路由</span>';
            }
        }

        // 清除结果
        function clearRoutingResult() {
            document.getElementById('routingResultCard').style.display = 'none';
            document.getElementById('routingInput').value = '';
            document.getElementById('routingOutput').innerHTML = '';
            document.getElementById('confidenceBar').style.width = '0%';
            currentRoutingResult = null;
        }

        // 复制结果
        function copyRoutingResult() {
            if (!currentRoutingResult) {
                alert('没有可复制的结果');
                return;
            }
            
            navigator.clipboard.writeText(currentRoutingResult.output)
                .then(() => {
                    alert('✅ 结果已复制到剪贴板');
                })
                .catch(err => {
                    console.error('复制失败:', err);
                    alert('复制失败，请手动复制');
                });
        }

        // ==================== Parallelization Agent 相关函数 ====================

        let parallelScenarios = [];
        let parallelStrategies = [];
        let parallelAggregationMethods = [];
        let currentParallelResult = null;
        let parallelTasksExpanded = false;

        // 页面加载时加载并行化场景
        window.addEventListener('load', async () => {
            try {
                await loadParallelizationScenarios();
            } catch (error) {
                console.error('加载并行化场景失败:', error);
            }
        });

        // 加载并行化场景
        async function loadParallelizationScenarios() {
            try {
                const response = await fetch(`${API_BASE}/api/parallelization/scenarios`);
                const data = await response.json();
                
                parallelScenarios = data.scenarios;
                parallelStrategies = data.strategies;
                parallelAggregationMethods = data.aggregation_methods;
                
                console.log('已加载并行化场景:', parallelScenarios);
                
            } catch (error) {
                console.error('加载并行化场景失败:', error);
            }
        }

        // 更新场景信息
        function updateParallelScenarioInfo() {
            const scenarioSelect = document.getElementById('parallelScenario');
            const scenarioId = scenarioSelect.value;
            const infoDiv = document.getElementById('parallelScenarioInfo');
            const inputTextarea = document.getElementById('parallelInput');
            const executeBtn = document.getElementById('parallelExecuteBtn');
            
            if (!scenarioId) {
                infoDiv.style.display = 'none';
                inputTextarea.placeholder = '请先选择一个场景...';
                executeBtn.disabled = true;
                return;
            }
            
            const scenario = parallelScenarios.find(s => s.id === scenarioId);
            if (!scenario) return;
            
            // 显示场景信息
            infoDiv.style.display = 'block';
            document.getElementById('parallelDescription').textContent = scenario.description;
            document.getElementById('parallelHint').innerHTML = `💡 ${scenario.input_hint}`;
            
            // 更新输入框提示
            inputTextarea.placeholder = scenario.input_hint;
            executeBtn.disabled = false;
        }

        // 执行并行化任务
        async function executeParallelization() {
            const scenarioId = document.getElementById('parallelScenario').value;
            const inputText = document.getElementById('parallelInput').value.trim();
            const strategy = document.getElementById('parallelStrategy').value;
            const aggregation = document.getElementById('parallelAggregation').value;
            const executeBtn = document.getElementById('parallelExecuteBtn');
            const progressCard = document.getElementById('parallelProgressCard');
            const resultCard = document.getElementById('parallelResultCard');
            
            if (!scenarioId) {
                alert('请先选择一个场景');
                return;
            }
            
            if (!inputText) {
                alert('请输入内容');
                return;
            }
            
            // 显示进度卡片
            progressCard.style.display = 'block';
            resultCard.style.display = 'none';
            
            // 重置进度
            document.getElementById('parallelProgressBar').style.width = '0%';
            document.getElementById('parallelProgressCount').textContent = '0 / 0';
            document.getElementById('parallelTaskStatus').innerHTML = '';
            
            // 禁用按钮
            executeBtn.disabled = true;
            executeBtn.innerHTML = '<span>⏳ 执行中...</span>';
            
            try {
                // 使用流式 API
                const response = await fetch(`${API_BASE}/api/parallelization/execute/stream`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        scenario: scenarioId,
                        input_text: inputText,
                        strategy: strategy,
                        aggregation: aggregation,
                        max_workers: 5,
                        batch_size: 3
                    })
                });
                
                if (!response.ok) {
                    throw new Error('请求失败');
                }
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                let totalTasks = 0;
                let completedTasks = 0;
                let taskResults = [];
                
                while (true) {
                    const { done, value } = await reader.read();
                    
                    if (done) break;
                    
                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n');
                    buffer = lines.pop() || '';
                    
                    for (const line of lines) {
                        if (!line.trim() || !line.startsWith('data: ')) continue;
                        
                        try {
                            const data = JSON.parse(line.slice(6));
                            
                            if (data.error) {
                                throw new Error(data.error);
                            }
                            
                            if (data.type === 'info') {
                                // 初始化信息
                                totalTasks = data.total_tasks;
                                document.getElementById('parallelProgressCount').textContent = `0 / ${totalTasks}`;
                                document.getElementById('parallelProgressText').textContent = `正在并行执行 ${totalTasks} 个任务...`;
                                
                            } else if (data.type === 'task_complete') {
                                // 任务完成
                                completedTasks = data.completed;
                                const progress = (completedTasks / totalTasks * 100).toFixed(0);
                                document.getElementById('parallelProgressBar').style.width = progress + '%';
                                document.getElementById('parallelProgressCount').textContent = `${completedTasks} / ${totalTasks}`;
                                
                                // 更新任务状态
                                const statusDiv = document.getElementById('parallelTaskStatus');
                                const taskStatusItem = document.createElement('div');
                                taskStatusItem.style.cssText = 'background: ' + (data.success ? '#d1fae5' : '#fee2e2') + '; padding: 8px 12px; border-radius: 6px; border: 2px solid ' + (data.success ? '#10b981' : '#ef4444') + ';';
                                taskStatusItem.innerHTML = `
                                    <div style="font-size: 12px; font-weight: 600; color: ${data.success ? '#065f46' : '#991b1b'};">
                                        ${data.success ? '✅' : '❌'} ${data.task_name}
                                    </div>
                                `;
                                statusDiv.appendChild(taskStatusItem);
                                
                            } else if (data.type === 'done') {
                                // 全部完成
                                document.getElementById('parallelProgressText').textContent = '✅ 并行执行完成';
                                document.getElementById('parallelProgressBar').style.width = '100%';
                                
                                // 显示结果卡片
                                resultCard.style.display = 'block';
                                
                                // 显示性能统计
                                const statsDiv = document.getElementById('parallelStats');
                                const speedup = data.success_count > 0 ? (data.total_time / (data.parallel_time || 1)).toFixed(2) : '1.00';
                                statsDiv.innerHTML = `
                                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 16px;">
                                        <div>
                                            <div style="font-size: 12px; color: #6c757d; margin-bottom: 4px;">总耗时</div>
                                            <div style="font-size: 20px; font-weight: 600; color: #667eea;">${data.total_time.toFixed(2)}s</div>
                                        </div>
                                        <div>
                                            <div style="font-size: 12px; color: #6c757d; margin-bottom: 4px;">并行耗时</div>
                                            <div style="font-size: 20px; font-weight: 600; color: #10b981;">${data.parallel_time.toFixed(2)}s</div>
                                        </div>
                                        <div>
                                            <div style="font-size: 12px; color: #6c757d; margin-bottom: 4px;">加速比</div>
                                            <div style="font-size: 20px; font-weight: 600; color: #f59e0b;">${speedup}x</div>
                                        </div>
                                        <div>
                                            <div style="font-size: 12px; color: #6c757d; margin-bottom: 4px;">成功/失败</div>
                                            <div style="font-size: 20px; font-weight: 600; color: #495057;">${data.success_count} / ${totalTasks - data.success_count}</div>
                                        </div>
                                    </div>
                                `;
                                
                                // 显示聚合结果
                                const aggregatedDiv = document.getElementById('parallelAggregatedResult');
                                if (typeof marked !== 'undefined' && typeof data.aggregated_result === 'string') {
                                    const html = marked.parse(data.aggregated_result);
                                    aggregatedDiv.innerHTML = DOMPurify.sanitize(html);
                                } else {
                                    aggregatedDiv.textContent = typeof data.aggregated_result === 'string' ? data.aggregated_result : JSON.stringify(data.aggregated_result, null, 2);
                                }
                                
                                // 显示各任务详细结果
                                const taskResultsDiv = document.getElementById('parallelTaskResults');
                                taskResultsDiv.innerHTML = '';
                                
                                data.task_results.forEach((result, index) => {
                                    const taskCard = document.createElement('div');
                                    taskCard.style.cssText = 'background: #f8f9fa; padding: 16px; border-radius: 8px; margin-bottom: 12px; border: 2px solid ' + (result.success ? '#dee2e6' : '#ef4444') + ';';
                                    
                                    const contentId = `task-content-${index}`;
                                    const isExpanded = parallelTasksExpanded;
                                    
                                    taskCard.innerHTML = `
                                        <div style="display: flex; justify-content: space-between; align-items: center; cursor: pointer;" onclick="toggleParallelTask('${contentId}')">
                                            <div>
                                                <h4 style="margin: 0 0 4px 0; color: #495057; font-size: 15px;">
                                                    ${result.success ? '✅' : '❌'} ${result.task_name}
                                                </h4>
                                                <div style="font-size: 12px; color: #6c757d;">
                                                    耗时: ${result.execution_time.toFixed(2)}s
                                                    ${result.error_message ? ` | 错误: ${result.error_message}` : ''}
                                                </div>
                                            </div>
                                            <span id="${contentId}-toggle" style="font-size: 18px; color: #6c757d;">
                                                ${isExpanded ? '▼' : '▶'}
                                            </span>
                                        </div>
                                        <div id="${contentId}" class="markdown-content" style="display: ${isExpanded ? 'block' : 'none'}; margin-top: 12px; padding-top: 12px; border-top: 1px solid #dee2e6; font-size: 13px;">
                                            ${result.success && result.output ? (typeof marked !== 'undefined' ? DOMPurify.sanitize(marked.parse(result.output)) : result.output) : (result.error_message || '执行失败')}
                                        </div>
                                    `;
                                    
                                    taskResultsDiv.appendChild(taskCard);
                                });
                                
                                // 保存结果
                                currentParallelResult = {
                                    scenario: scenarioId,
                                    aggregated_result: data.aggregated_result,
                                    task_results: data.task_results,
                                    total_time: data.total_time,
                                    parallel_time: data.parallel_time,
                                    success_count: data.success_count
                                };
                                
                                // 滚动到结果
                                resultCard.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                            }
                        } catch (e) {
                            console.error('解析SSE数据失败:', e);
                        }
                    }
                }
                
            } catch (error) {
                console.error('执行失败:', error);
                alert('执行失败: ' + error.message);
                
            } finally {
                // 恢复按钮
                executeBtn.disabled = false;
                executeBtn.innerHTML = '<span>🚀 执行并行任务</span>';
            }
        }

        // 切换单个任务的展开/折叠
        function toggleParallelTask(contentId) {
            const contentDiv = document.getElementById(contentId);
            const toggleSpan = document.getElementById(contentId + '-toggle');
            
            if (contentDiv.style.display === 'none') {
                contentDiv.style.display = 'block';
                toggleSpan.textContent = '▼';
            } else {
                contentDiv.style.display = 'none';
                toggleSpan.textContent = '▶';
            }
        }

        // 切换所有任务的展开/折叠
        function toggleAllParallelTasks() {
            parallelTasksExpanded = !parallelTasksExpanded;
            const btn = document.getElementById('toggleAllTasksBtn');
            btn.textContent = parallelTasksExpanded ? '折叠全部' : '展开全部';
            
            // 切换所有任务
            document.querySelectorAll('#parallelTaskResults [id^="task-content-"]').forEach(div => {
                if (div.id.endsWith('-toggle')) return;
                div.style.display = parallelTasksExpanded ? 'block' : 'none';
                
                const toggleSpan = document.getElementById(div.id + '-toggle');
                if (toggleSpan) {
                    toggleSpan.textContent = parallelTasksExpanded ? '▼' : '▶';
                }
            });
        }

        // 清除结果
        function clearParallelResult() {
            document.getElementById('parallelProgressCard').style.display = 'none';
            document.getElementById('parallelResultCard').style.display = 'none';
            document.getElementById('parallelInput').value = '';
            document.getElementById('parallelProgressBar').style.width = '0%';
            document.getElementById('parallelTaskStatus').innerHTML = '';
            document.getElementById('parallelAggregatedResult').innerHTML = '';
            document.getElementById('parallelTaskResults').innerHTML = '';
            currentParallelResult = null;
            parallelTasksExpanded = false;
        }

        // 复制结果
        function copyParallelResult() {
            if (!currentParallelResult) {
                alert('没有可复制的结果');
                return;
            }
            
            const text = typeof currentParallelResult.aggregated_result === 'string' 
                ? currentParallelResult.aggregated_result 
                : JSON.stringify(currentParallelResult.aggregated_result, null, 2);
            
            navigator.clipboard.writeText(text)
                .then(() => {
                    alert('✅ 结果已复制到剪贴板');
                })
                .catch(err => {
                    console.error('复制失败:', err);
                    alert('复制失败，请手动复制');
                });
        }

        // 下载结果
        function downloadParallelResult() {
            if (!currentParallelResult) {
                alert('没有可下载的结果');
                return;
            }
            
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
            const filename = `parallel_result_${currentParallelResult.scenario}_${timestamp}.md`;
            
            let content = `# 并行化执行结果\n\n`;
            content += `**场景:** ${currentParallelResult.scenario}\n`;
            content += `**生成时间:** ${new Date().toLocaleString('zh-CN')}\n`;
            content += `**总耗时:** ${currentParallelResult.total_time.toFixed(2)}s\n`;
            content += `**并行耗时:** ${currentParallelResult.parallel_time.toFixed(2)}s\n`;
            content += `**成功任务:** ${currentParallelResult.success_count}\n\n`;
            content += `---\n\n`;
            content += `## 聚合结果\n\n`;
            content += typeof currentParallelResult.aggregated_result === 'string' 
                ? currentParallelResult.aggregated_result 
                : JSON.stringify(currentParallelResult.aggregated_result, null, 2);
            content += `\n\n---\n\n`;
            content += `## 各任务详细结果\n\n`;
            
            currentParallelResult.task_results.forEach((result, index) => {
                content += `### ${index + 1}. ${result.task_name}\n\n`;
                content += `**状态:** ${result.success ? '✅ 成功' : '❌ 失败'}\n`;
                content += `**耗时:** ${result.execution_time.toFixed(2)}s\n\n`;
                if (result.success && result.output) {
                    content += result.output + '\n\n';
                } else if (result.error_message) {
                    content += `**错误:** ${result.error_message}\n\n`;
                }
                content += `---\n\n`;
            });
            
            const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            console.log('已下载结果到:', filename);
        }

        // ==================== Reflection Agent 相关函数 ====================

        let reflectionScenarios = [];
        let reflectionHistory = [];

        // 加载反思场景
        async function loadReflectionScenarios() {
            try {
                const response = await fetch(`${API_BASE}/api/reflection/scenarios`);
                const data = await response.json();
                reflectionScenarios = data.scenarios;
            } catch (error) {
                console.error('加载反思场景失败:', error);
            }
        }

        // 更新反思场景信息
        function updateReflectionScenarioInfo() {
            const scenario = document.getElementById('reflectionScenario').value;
            const info = reflectionScenarios.find(s => s.id === scenario);
            
            if (info) {
                document.getElementById('reflectionScenarioInfo').style.display = 'block';
                document.getElementById('reflectionDescription').textContent = info.description;
                document.getElementById('reflectionHint').textContent = '💡 ' + info.input_hint;
                
                // 显示反思标准
                const criteriaHtml = '<strong>评估标准：</strong>' + info.criteria.map(c => `<span style="display: inline-block; background: #e7f5ff; padding: 4px 8px; border-radius: 4px; margin: 2px; font-size: 12px;">${c}</span>`).join('');
                document.getElementById('reflectionCriteria').innerHTML = criteriaHtml;
                
                document.getElementById('reflectionInput').placeholder = info.input_hint;
            } else {
                document.getElementById('reflectionScenarioInfo').style.display = 'none';
                document.getElementById('reflectionInput').placeholder = '请先选择一个场景...';
            }
        }

        // 更新反思策略信息（显示/隐藏专家设置）
        function updateReflectionStrategyInfo() {
            const strategy = document.getElementById('reflectionStrategy').value;
            const expertSettings = document.getElementById('expertSettings');
            
            if (strategy === 'expert') {
                expertSettings.style.display = 'block';
            } else {
                expertSettings.style.display = 'none';
            }
        }

        // 执行反思
        async function executeReflection() {
            const scenario = document.getElementById('reflectionScenario').value;
            const strategy = document.getElementById('reflectionStrategy').value;
            const input = document.getElementById('reflectionInput').value.trim();
            const maxIterations = parseInt(document.getElementById('maxIterations').value);
            const scoreThreshold = parseFloat(document.getElementById('scoreThreshold').value);
            
            if (!scenario) {
                alert('请先选择一个场景');
                return;
            }
            
            if (!input) {
                alert('请输入任务描述或初始内容');
                return;
            }
            
            const btn = document.getElementById('reflectionExecuteBtn');
            btn.disabled = true;
            btn.innerHTML = '<span>⏳ 正在执行反思...</span>';
            
            // 显示进度卡片
            document.getElementById('reflectionProgressCard').style.display = 'block';
            document.getElementById('reflectionHistoryCard').style.display = 'none';
            document.getElementById('reflectionResultCard').style.display = 'none';
            
            reflectionHistory = [];
            let initialScore = 0;
            
            try {
                // 准备请求数据
                const requestData = {
                    task: input,
                    scenario: scenario,
                    strategy: strategy,
                    max_iterations: maxIterations,
                    score_threshold: scoreThreshold
                };
                
                // 如果是专家策略，添加专家信息
                if (strategy === 'expert') {
                    const expertRole = document.getElementById('expertRole').value.trim();
                    const expertExpertise = document.getElementById('expertExpertise').value.trim();
                    if (expertRole) requestData.expert_role = expertRole;
                    if (expertExpertise) requestData.expert_expertise = expertExpertise;
                }
                
                // 使用流式API
                const response = await fetch(`${API_BASE}/api/reflection/reflect/stream`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(requestData)
                });
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                
                while (true) {
                    const { value, done } = await reader.read();
                    if (done) break;
                    
                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n');
                    buffer = lines.pop();
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = JSON.parse(line.slice(6));
                            
                            if (data.error) {
                                throw new Error(data.error);
                            }
                            
                            if (data.type === 'info') {
                                document.getElementById('reflectionProgressText').textContent = 
                                    `最大迭代次数: ${data.max_iterations}, 策略: ${data.strategy}`;
                            } else if (data.type === 'generating') {
                                document.getElementById('reflectionStepMessage').textContent = data.message;
                            } else if (data.type === 'initial_content') {
                                document.getElementById('reflectionStepMessage').innerHTML = 
                                    `<strong>初始内容已生成</strong><br><div style="margin-top: 8px; padding: 12px; background: white; border-radius: 6px; max-height: 200px; overflow-y: auto;">${data.content.substring(0, 300)}...</div>`;
                            } else if (data.type === 'iteration_start') {
                                document.getElementById('reflectionIterationCount').textContent = `第 ${data.iteration} 轮`;
                                document.getElementById('reflectionProgressBar').style.width = 
                                    `${(data.iteration / maxIterations) * 100}%`;
                                document.getElementById('reflectionStepMessage').textContent = 
                                    `正在进行第 ${data.iteration} 轮反思...`;
                            } else if (data.type === 'reflection') {
                                // 记录历史
                                reflectionHistory.push({
                                    iteration: data.iteration,
                                    critique: data.critique,
                                    score: data.score,
                                    improvements: data.improvements
                                });
                                
                                if (data.iteration === 1) {
                                    initialScore = data.score;
                                }
                                
                                // 确保critique是字符串
                                const critiqueText = typeof data.critique === 'string' ? data.critique : JSON.stringify(data.critique);
                                const critiquePreview = critiqueText.length > 200 ? critiqueText.substring(0, 200) + '...' : critiqueText;
                                
                                // 更新进度信息
                                document.getElementById('reflectionStepMessage').innerHTML = 
                                    `<strong>第 ${data.iteration} 轮反思完成</strong><br>` +
                                    `评分: <strong>${data.score.toFixed(2)}</strong><br>` +
                                    `<div style="margin-top: 8px; padding: 12px; background: white; border-radius: 6px;">${critiquePreview}</div>`;
                                
                                // 显示反思历史
                                displayReflectionHistory();
                            } else if (data.type === 'threshold_reached') {
                                document.getElementById('reflectionStepMessage').innerHTML = 
                                    `<strong style="color: #28a745;">✅ 已达到质量阈值！</strong><br>` +
                                    `评分 ${data.score.toFixed(2)} >= ${data.threshold}`;
                            } else if (data.type === 'improving') {
                                document.getElementById('reflectionStepMessage').textContent = data.message;
                            } else if (data.type === 'improved_content') {
                                document.getElementById('reflectionStepMessage').innerHTML = 
                                    `<strong>第 ${data.iteration} 轮改进完成</strong><br>` +
                                    `<div style="margin-top: 8px; padding: 12px; background: white; border-radius: 6px; max-height: 200px; overflow-y: auto;">${data.content.substring(0, 300)}...</div>`;
                            } else if (data.type === 'done') {
                                // 显示最终结果
                                displayReflectionResult(data, initialScore);
                                
                                // 隐藏进度卡片
                                document.getElementById('reflectionProgressCard').style.display = 'none';
                            }
                        }
                    }
                }
                
            } catch (error) {
                console.error('反思执行失败:', error);
                alert('反思执行失败: ' + error.message);
                document.getElementById('reflectionProgressCard').style.display = 'none';
            } finally {
                btn.disabled = false;
                btn.innerHTML = '<span>💭 开始反思与改进</span>';
            }
        }

        // 显示反思历史
        function displayReflectionHistory() {
            const historyDiv = document.getElementById('reflectionHistory');
            historyDiv.innerHTML = '';
            
            reflectionHistory.forEach(item => {
                const historyItem = document.createElement('div');
                historyItem.style.cssText = 'background: #f8f9fa; padding: 16px; border-radius: 8px; border-left: 4px solid #667eea;';
                
                // 确保improvements是数组
                const improvements = Array.isArray(item.improvements) ? item.improvements : [];
                const improvementsHtml = improvements.map(imp => 
                    `<li style="margin: 4px 0;">${imp}</li>`
                ).join('');
                
                // 确保critique是字符串
                const critiqueText = typeof item.critique === 'string' ? item.critique : JSON.stringify(item.critique);
                
                historyItem.innerHTML = `
                    <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                        <h4 style="margin: 0; color: #495057;">第 ${item.iteration} 轮反思</h4>
                        <span style="background: ${item.score >= 0.8 ? '#d1f4e0' : item.score >= 0.6 ? '#fff3cd' : '#f8d7da'}; 
                                     color: ${item.score >= 0.8 ? '#155724' : item.score >= 0.6 ? '#856404' : '#721c24'}; 
                                     padding: 4px 12px; border-radius: 12px; font-weight: 600;">
                            ${item.score.toFixed(2)}
                        </span>
                    </div>
                    <div style="margin: 12px 0; color: #6c757d;">${critiqueText}</div>
                    <div style="margin-top: 12px;">
                        <strong style="color: #495057;">改进建议：</strong>
                        <ul style="margin: 8px 0; padding-left: 24px; color: #6c757d;">${improvementsHtml}</ul>
                    </div>
                `;
                
                historyDiv.appendChild(historyItem);
            });
            
            document.getElementById('reflectionHistoryCard').style.display = 'block';
        }

        // 显示反思结果
        function displayReflectionResult(data, initialScore) {
            // 统计信息
            document.getElementById('finalScore').textContent = data.final_score.toFixed(2);
            document.getElementById('totalIterations').textContent = data.total_iterations;
            const improvement = data.final_score - initialScore;
            document.getElementById('scoreImprovement').textContent = 
                (improvement >= 0 ? '+' : '') + improvement.toFixed(2);
            document.getElementById('reflectionTime').textContent = data.total_iterations + '轮';
            
            // 最终内容
            if (typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined') {
                const rawHtml = marked.parse(data.final_content);
                const cleanHtml = DOMPurify.sanitize(rawHtml);
                document.getElementById('reflectionFinalContent').innerHTML = cleanHtml;
            } else {
                document.getElementById('reflectionFinalContent').textContent = data.final_content;
            }
            
            // 改进总结
            if (typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined') {
                const rawHtml = marked.parse(data.improvement_summary);
                const cleanHtml = DOMPurify.sanitize(rawHtml);
                document.getElementById('reflectionSummary').innerHTML = cleanHtml;
            } else {
                document.getElementById('reflectionSummary').textContent = data.improvement_summary;
            }
            
            // 显示结果卡片
            document.getElementById('reflectionResultCard').style.display = 'block';
        }

        // 清除反思结果
        function clearReflectionResult() {
            reflectionHistory = [];
            document.getElementById('reflectionProgressCard').style.display = 'none';
            document.getElementById('reflectionHistoryCard').style.display = 'none';
            document.getElementById('reflectionResultCard').style.display = 'none';
            document.getElementById('reflectionProgressBar').style.width = '0%';
        }

        // 复制反思结果
        function copyReflectionResult() {
            const content = document.getElementById('reflectionFinalContent').textContent;
            navigator.clipboard.writeText(content).then(() => {
                alert('结果已复制到剪贴板！');
            }).catch(err => {
                console.error('复制失败:', err);
                alert('复制失败，请手动复制');
            });
        }

        // 下载反思结果
        function downloadReflectionResult() {
            const content = document.getElementById('reflectionFinalContent').textContent;
            const summary = document.getElementById('reflectionSummary').textContent;
            
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
            const filename = `reflection_result_${timestamp}.md`;
            
            let fullContent = `# Reflection Agent 反思结果\n\n`;
            fullContent += `**生成时间**: ${new Date().toLocaleString('zh-CN')}\n\n`;
            fullContent += `---\n\n`;
            fullContent += `## 最终内容\n\n${content}\n\n`;
            fullContent += `---\n\n`;
            fullContent += `## 改进总结\n\n${summary}\n\n`;
            fullContent += `---\n\n`;
            fullContent += `## 反思历史\n\n`;
            
            reflectionHistory.forEach(item => {
                fullContent += `### 第 ${item.iteration} 轮 (评分: ${item.score.toFixed(2)})\n\n`;
                fullContent += `**批评**: ${item.critique}\n\n`;
                fullContent += `**改进建议**:\n`;
                item.improvements.forEach(imp => {
                    fullContent += `- ${imp}\n`;
                });
                fullContent += `\n`;
            });
            
            const blob = new Blob([fullContent], { type: 'text/markdown;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            console.log('已下载反思结果到:', filename);
        }

        // 显示完整反思历史
        function showReflectionHistory() {
            const card = document.getElementById('reflectionHistoryCard');
            if (card.style.display === 'none') {
                card.style.display = 'block';
                card.scrollIntoView({ behavior: 'smooth', block: 'start' });
            } else {
                card.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        }

        // ==================== Tool Use Agent 功能 ====================
        
        let toolUseHistory = [];
        let currentToolUseExecution = null;

        // 设置快速任务
        function setQuickTask(task) {
            document.getElementById('toolUseInput').value = task;
        }

        // 更新工具类型信息
        function updateToolTypeInfo() {
            const toolType = document.getElementById('toolTypeFilter').value;
            const infoDiv = document.getElementById('toolTypeInfo');
            const descDiv = document.getElementById('toolTypeDescription');
            const examplesDiv = document.getElementById('toolTypeExamples');
            
            if (!toolType) {
                infoDiv.style.display = 'none';
                return;
            }
            
            const toolTypeInfo = {
                'file_operation': {
                    description: '文件和目录的读写操作工具',
                    examples: ['读取文件内容', '写入文件', '列出目录', '获取文件信息']
                },
                'network_request': {
                    description: 'HTTP请求和网络通信工具',
                    examples: ['GET请求获取数据', 'POST提交数据', 'Ping测试连通性']
                },
                'data_processing': {
                    description: '数据解析、转换和分析工具',
                    examples: ['JSON解析', '数据过滤', '数据聚合', 'CSV处理']
                },
                'system_info': {
                    description: '系统状态和性能监控工具',
                    examples: ['CPU使用率', '内存信息', '磁盘空间', '进程列表']
                },
                'calculation': {
                    description: '数学计算和统计分析工具',
                    examples: ['数学表达式计算', '统计分析', '单位转换']
                },
                'text_processing': {
                    description: '文本分析和处理工具',
                    examples: ['文本统计', '搜索替换', '正则匹配', '哈希计算']
                }
            };
            
            const info = toolTypeInfo[toolType];
            if (info) {
                descDiv.textContent = info.description;
                examplesDiv.innerHTML = '<strong>示例任务：</strong> ' + info.examples.join('、');
                infoDiv.style.display = 'block';
            }
        }

        // 执行Tool Use任务
        async function executeToolUse() {
            const input = document.getElementById('toolUseInput').value.trim();
            if (!input) {
                alert('请输入任务描述');
                return;
            }
            
            const maxIterations = parseInt(document.getElementById('maxIterations').value);
            const toolType = document.getElementById('toolTypeFilter').value;
            
            const executeBtn = document.getElementById('toolUseExecuteBtn');
            const streamBtn = document.getElementById('toolUseStreamBtn');
            
            executeBtn.disabled = true;
            streamBtn.disabled = true;
            executeBtn.textContent = '🔄 执行中...';
            
            // 显示进度
            showToolUseProgress();
            
            try {
                const response = await fetch(`${API_BASE}/api/tool-use/execute`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        user_input: input,
                        max_iterations: maxIterations,
                        tool_type: toolType || null
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                
                if (data.success) {
                    displayToolUseResult(data);
                    displayToolUseHistory(data.results || []);
                } else {
                    throw new Error(data.message || '执行失败');
                }
                
            } catch (error) {
                console.error('Tool Use执行失败:', error);
                alert(`执行失败: ${error.message}`);
                hideToolUseProgress();
            } finally {
                executeBtn.disabled = false;
                streamBtn.disabled = false;
                executeBtn.textContent = '🔧 执行任务';
            }
        }

        // 流式执行Tool Use任务
        async function executeToolUseStream() {
            const input = document.getElementById('toolUseInput').value.trim();
            if (!input) {
                alert('请输入任务描述');
                return;
            }
            
            const maxIterations = parseInt(document.getElementById('maxIterations').value);
            const toolType = document.getElementById('toolTypeFilter').value;
            
            const executeBtn = document.getElementById('toolUseExecuteBtn');
            const streamBtn = document.getElementById('toolUseStreamBtn');
            
            executeBtn.disabled = true;
            streamBtn.disabled = true;
            streamBtn.textContent = '📡 流式执行中...';
            
            // 显示进度
            showToolUseProgress();
            clearToolUseHistory();
            
            try {
                const response = await fetch(`${API_BASE}/api/tool-use/execute/stream`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        user_input: input,
                        max_iterations: maxIterations,
                        tool_type: toolType || null
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;
                    
                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(6));
                                handleToolUseStreamData(data);
                            } catch (e) {
                                console.warn('解析流数据失败:', e);
                            }
                        }
                    }
                }
                
            } catch (error) {
                console.error('流式执行失败:', error);
                alert(`流式执行失败: ${error.message}`);
                hideToolUseProgress();
            } finally {
                executeBtn.disabled = false;
                streamBtn.disabled = false;
                streamBtn.textContent = '📡 流式执行';
            }
        }

        // 处理流式数据
        function handleToolUseStreamData(data) {
            switch (data.type) {
                case 'start':
                    updateToolUseProgress(0, data.message);
                    break;
                case 'step':
                    updateToolUseProgress((data.step / 5) * 100, `第${data.step}步: ${data.result.tool_name}`);
                    addToolUseHistoryItem(data.result);
                    break;
                case 'complete':
                    updateToolUseProgress(100, '执行完成');
                    displayToolUseResult(data.final_result);
                    break;
                case 'error':
                    alert(`执行出错: ${data.message}`);
                    hideToolUseProgress();
                    break;
            }
        }

        // 显示进度
        function showToolUseProgress() {
            document.getElementById('toolUseProgressCard').style.display = 'block';
            document.getElementById('toolUseHistoryCard').style.display = 'block';
            updateToolUseProgress(0, '准备执行...');
        }

        // 更新进度
        function updateToolUseProgress(percent, message) {
            document.getElementById('toolUseProgressBar').style.width = `${percent}%`;
            document.getElementById('toolUseCurrentStep').textContent = message;
        }

        // 隐藏进度
        function hideToolUseProgress() {
            document.getElementById('toolUseProgressCard').style.display = 'none';
        }

        // 显示Tool Use结果
        function displayToolUseResult(data) {
            // 统计信息
            document.getElementById('toolUseSuccess').textContent = data.success ? '成功' : '失败';
            document.getElementById('toolUseIterations').textContent = data.total_iterations || 0;
            
            const toolsUsed = new Set();
            (data.results || []).forEach(result => {
                if (result.tool_name) toolsUsed.add(result.tool_name);
            });
            document.getElementById('toolUseToolsUsed').textContent = toolsUsed.size;
            
            const totalTime = (data.results || []).reduce((sum, result) => sum + (result.execution_time || 0), 0);
            document.getElementById('toolUseTime').textContent = `${totalTime.toFixed(2)}s`;
            
            // 最终结果
            let finalResult = data.message || '任务完成';
            if (data.results && data.results.length > 0) {
                const lastResult = data.results[data.results.length - 1];
                if (lastResult.result) {
                    finalResult = lastResult.result;
                }
            }
            
            if (typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined') {
                const rawHtml = marked.parse(String(finalResult));
                const cleanHtml = DOMPurify.sanitize(rawHtml);
                document.getElementById('toolUseFinalResult').innerHTML = cleanHtml;
            } else {
                document.getElementById('toolUseFinalResult').textContent = finalResult;
            }
            
            // 显示结果卡片
            document.getElementById('toolUseResultCard').style.display = 'block';
            hideToolUseProgress();
        }

        // 显示Tool Use历史
        function displayToolUseHistory(results) {
            toolUseHistory = results;
            const historyDiv = document.getElementById('toolUseHistory');
            historyDiv.innerHTML = '';
            
            results.forEach((result, index) => {
                addToolUseHistoryItem(result, index + 1);
            });
        }

        // 添加历史项
        function addToolUseHistoryItem(result, step) {
            const historyDiv = document.getElementById('toolUseHistory');
            const historyItem = document.createElement('div');
            historyItem.className = 'history-item';
            historyItem.style.cssText = `
                background: ${result.success ? '#d1f4e0' : '#f8d7da'};
                border-left: 4px solid ${result.success ? '#28a745' : '#dc3545'};
                padding: 16px;
                margin-bottom: 12px;
                border-radius: 8px;
            `;
            
            const stepNum = step || toolUseHistory.length + 1;
            const executionTime = result.execution_time ? `${result.execution_time.toFixed(2)}s` : '-';
            
            historyItem.innerHTML = `
                <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                    <h4 style="margin: 0; color: #495057;">步骤 ${stepNum}: ${result.tool_name}</h4>
                    <span style="background: rgba(0,0,0,0.1); padding: 4px 8px; border-radius: 4px; font-size: 12px;">
                        ${executionTime}
                    </span>
                </div>
                <div style="margin: 8px 0; color: #6c757d; font-size: 14px;">
                    <strong>推理:</strong> ${result.reasoning || '自动选择'}
                </div>
                <div style="margin: 8px 0; color: #6c757d; font-size: 14px;">
                    <strong>参数:</strong> ${JSON.stringify(result.parameters || {})}
                </div>
                <div style="margin-top: 8px;">
                    <strong style="color: #495057;">结果:</strong>
                    <div style="background: rgba(255,255,255,0.7); padding: 12px; border-radius: 4px; margin-top: 4px; font-family: monospace; font-size: 13px; max-height: 200px; overflow-y: auto;">
                        ${result.success ? String(result.result).substring(0, 500) : result.error_message}
                        ${String(result.result || result.error_message || '').length > 500 ? '...' : ''}
                    </div>
                </div>
            `;
            
            historyDiv.appendChild(historyItem);
        }

        // 清除Tool Use历史
        function clearToolUseHistory() {
            document.getElementById('toolUseHistory').innerHTML = '';
            toolUseHistory = [];
        }

        // 清除Tool Use结果
        function clearToolUseResult() {
            toolUseHistory = [];
            document.getElementById('toolUseProgressCard').style.display = 'none';
            document.getElementById('toolUseHistoryCard').style.display = 'none';
            document.getElementById('toolUseResultCard').style.display = 'none';
            document.getElementById('availableToolsCard').style.display = 'none';
            document.getElementById('toolUseProgressBar').style.width = '0%';
            clearToolUseHistory();
        }

        // 复制Tool Use结果
        function copyToolUseResult() {
            const content = document.getElementById('toolUseFinalResult').textContent;
            navigator.clipboard.writeText(content).then(() => {
                alert('结果已复制到剪贴板！');
            }).catch(err => {
                console.error('复制失败:', err);
                alert('复制失败，请手动复制');
            });
        }

        // 下载Tool Use结果
        function downloadToolUseResult() {
            const content = document.getElementById('toolUseFinalResult').textContent;
            
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
            const filename = `tool_use_result_${timestamp}.md`;
            
            let fullContent = `# Tool Use Agent 执行结果\n\n`;
            fullContent += `**生成时间**: ${new Date().toLocaleString('zh-CN')}\n\n`;
            fullContent += `---\n\n`;
            fullContent += `## 最终结果\n\n${content}\n\n`;
            fullContent += `---\n\n`;
            fullContent += `## 执行历史\n\n`;
            
            toolUseHistory.forEach((result, index) => {
                fullContent += `### 步骤 ${index + 1}: ${result.tool_name}\n\n`;
                fullContent += `**推理**: ${result.reasoning || '自动选择'}\n\n`;
                fullContent += `**参数**: \`${JSON.stringify(result.parameters || {})}\`\n\n`;
                fullContent += `**结果**: ${result.success ? result.result : result.error_message}\n\n`;
                fullContent += `**执行时间**: ${result.execution_time ? result.execution_time.toFixed(2) + 's' : '-'}\n\n`;
            });
            
            const blob = new Blob([fullContent], { type: 'text/markdown;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            console.log('已下载Tool Use结果到:', filename);
        }

        // 显示可用工具
        async function showAvailableTools() {
            const toolType = document.getElementById('toolTypeFilter').value;
            
            try {
                const url = `${API_BASE}/api/tool-use/tools${toolType ? `?tool_type=${toolType}` : ''}`;
                const response = await fetch(url);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                displayAvailableTools(data.tools);
                
            } catch (error) {
                console.error('获取工具列表失败:', error);
                alert(`获取工具列表失败: ${error.message}`);
            }
        }

        // 显示可用工具列表
        function displayAvailableTools(tools) {
            const toolsDiv = document.getElementById('availableToolsList');
            toolsDiv.innerHTML = '';
            
            tools.forEach(tool => {
                const toolItem = document.createElement('div');
                toolItem.style.cssText = `
                    background: #f8f9fa;
                    border: 1px solid #dee2e6;
                    border-radius: 8px;
                    padding: 16px;
                    margin-bottom: 12px;
                `;
                
                const parametersHtml = tool.parameters.map(param => {
                    return `<li><strong>${param.name}</strong> (${param.type})${param.required ? ' [必需]' : ' [可选]'}: ${param.description}</li>`;
                }).join('');
                
                const examplesHtml = tool.examples.length > 0 ? 
                    `<div style="margin-top: 8px;"><strong>示例:</strong> ${tool.examples.join('、')}</div>` : '';
                
                toolItem.innerHTML = `
                    <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 8px;">
                        <h4 style="margin: 0; color: #495057;">${tool.name}</h4>
                        <span style="background: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-size: 12px;">
                            ${tool.type}
                        </span>
                    </div>
                    <div style="color: #6c757d; margin-bottom: 12px;">${tool.description}</div>
                    <div style="margin-bottom: 8px;">
                        <strong>参数:</strong>
                        <ul style="margin: 4px 0; padding-left: 20px; font-size: 13px;">${parametersHtml}</ul>
                    </div>
                    ${examplesHtml}
                `;
                
                toolsDiv.appendChild(toolItem);
            });
            
            document.getElementById('availableToolsCard').style.display = 'block';
        }

        // 显示工具历史
        async function showToolHistory() {
            try {
                const response = await fetch(`${API_BASE}/api/tool-use/history`);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                displayToolHistoryModal(data.history, data.statistics);
                
            } catch (error) {
                console.error('获取工具历史失败:', error);
                alert(`获取工具历史失败: ${error.message}`);
            }
        }

        // 显示工具历史模态框
        function displayToolHistoryModal(history, statistics) {
            // 简化实现：使用alert显示统计信息
            let message = `工具使用统计:\n`;
            message += `总执行次数: ${statistics.total_executions}\n`;
            message += `成功次数: ${statistics.successful_executions}\n`;
            message += `失败次数: ${statistics.failed_executions}\n`;
            message += `平均执行时间: ${statistics.average_execution_time?.toFixed(2)}s\n\n`;
            
            if (statistics.most_used_tools && statistics.most_used_tools.length > 0) {
                message += `最常用工具:\n`;
                statistics.most_used_tools.forEach(([tool, count]) => {
                    message += `- ${tool}: ${count}次\n`;
                });
            }
            
            alert(message);
        }

        // 显示Tool Use历史详情
        function showToolUseHistory() {
            const card = document.getElementById('toolUseHistoryCard');
            if (card.style.display === 'none') {
                card.style.display = 'block';
                card.scrollIntoView({ behavior: 'smooth', block: 'start' });
            } else {
                card.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        }

        // Planning Agent 相关函数
        let currentPlanId = null;

        async function createPlanning() {
            const goal = document.getElementById('planningGoal').value.trim();
            const scenario = document.getElementById('planningScenario').value;
            const strategy = document.getElementById('planningStrategy').value;
            const autoExecute = document.getElementById('autoExecute').checked;
            
            if (!goal) {
                alert('请输入目标描述');
                return;
            }

            const btn = document.getElementById('planningCreateBtn');
            btn.disabled = true;
            btn.textContent = '📋 创建中...';

            showPlanningProgress();
            updatePlanningProgress(20, '正在分析目标...');

            try {
                const response = await fetch('/api/planning/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        goal: goal,
                        scenario: scenario || null,
                        strategy: strategy,
                        auto_execute: autoExecute
                    })
                });

                updatePlanningProgress(60, '正在生成计划...');

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                updatePlanningProgress(100, '计划创建完成！');

                setTimeout(() => {
                    hidePlanningProgress();
                    displayPlanningResult(data);
                    
                    if (data.execution_result) {
                        displayExecutionResult(data.execution_result);
                    }
                }, 1000);

            } catch (error) {
                console.error('创建规划失败:', error);
                hidePlanningProgress();
                alert('创建规划失败: ' + error.message);
            } finally {
                btn.disabled = false;
                btn.textContent = '📋 创建计划';
            }
        }

        async function executePlan() {
            if (!currentPlanId) {
                alert('没有可执行的计划');
                return;
            }

            const btn = document.getElementById('executePlanBtn');
            btn.disabled = true;
            btn.textContent = '▶️ 执行中...';

            showExecutionProgress();
            updateExecutionProgress(0, '准备执行计划...');

            try {
                const response = await fetch('/api/planning/execute', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        plan_id: currentPlanId
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                hideExecutionProgress();
                displayExecutionResult(data);

            } catch (error) {
                console.error('执行计划失败:', error);
                hideExecutionProgress();
                alert('执行计划失败: ' + error.message);
            } finally {
                btn.disabled = false;
                btn.textContent = '▶️ 执行计划';
            }
        }

        async function executePlanStream() {
            if (!currentPlanId) {
                alert('没有可执行的计划');
                return;
            }

            const btn = document.getElementById('executePlanStreamBtn');
            btn.disabled = true;
            btn.textContent = '📡 执行中...';

            showExecutionProgress();
            showExecutionLog();

            try {
                const response = await fetch('/api/planning/execute/stream', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        plan_id: currentPlanId
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(6));
                                handlePlanningStreamData(data);
                            } catch (e) {
                                console.error('解析流数据失败:', e);
                            }
                        }
                    }
                }

            } catch (error) {
                console.error('流式执行失败:', error);
                hideExecutionProgress();
                alert('流式执行失败: ' + error.message);
            } finally {
                btn.disabled = false;
                btn.textContent = '📡 流式执行';
            }
        }

        function handlePlanningStreamData(data) {
            switch (data.type) {
                case 'start':
                    updateExecutionProgress(0, data.message);
                    addExecutionLogItem('INFO', data.message);
                    break;
                case 'progress':
                    updateExecutionProgress(data.progress * 100, `执行任务: ${data.current_task?.name || '未知'}`);
                    if (data.current_task) {
                        addExecutionLogItem('INFO', `开始执行: ${data.current_task.name}`);
                    }
                    break;
                case 'complete':
                    updateExecutionProgress(100, '执行完成！');
                    addExecutionLogItem('SUCCESS', '计划执行完成');
                    setTimeout(() => {
                        hideExecutionProgress();
                        displayExecutionResult(data);
                    }, 1000);
                    break;
                case 'error':
                    addExecutionLogItem('ERROR', data.message);
                    break;
            }
        }

        function showPlanningProgress() {
            document.getElementById('planningProgressCard').style.display = 'block';
            document.getElementById('planningProgressCard').scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        function updatePlanningProgress(percent, message) {
            document.getElementById('planningProgressBar').style.width = percent + '%';
            document.getElementById('planningCurrentStep').textContent = message;
        }

        function hidePlanningProgress() {
            document.getElementById('planningProgressCard').style.display = 'none';
        }

        function showExecutionProgress() {
            document.getElementById('executionProgressCard').style.display = 'block';
            document.getElementById('executionProgressCard').scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        function updateExecutionProgress(percent, message) {
            document.getElementById('executionProgressBar').style.width = percent + '%';
            document.getElementById('executionCurrentTask').textContent = message;
        }

        function hideExecutionProgress() {
            document.getElementById('executionProgressCard').style.display = 'none';
        }

        function showExecutionLog() {
            const logCard = document.getElementById('executionLogCard');
            logCard.style.display = 'block';
            document.getElementById('executionLog').innerHTML = '';
        }

        function addExecutionLogItem(level, message) {
            const logContainer = document.getElementById('executionLog');
            const logItem = document.createElement('div');
            logItem.style.cssText = 'padding: 8px 12px; margin-bottom: 8px; border-radius: 6px; font-size: 14px;';
            
            const timestamp = new Date().toLocaleTimeString();
            let bgColor, textColor, icon;
            
            switch (level) {
                case 'INFO':
                    bgColor = '#e7f3ff';
                    textColor = '#004085';
                    icon = 'ℹ️';
                    break;
                case 'SUCCESS':
                    bgColor = '#d1f4e0';
                    textColor = '#155724';
                    icon = '✅';
                    break;
                case 'ERROR':
                    bgColor = '#f8d7da';
                    textColor = '#721c24';
                    icon = '❌';
                    break;
                default:
                    bgColor = '#f8f9fa';
                    textColor = '#495057';
                    icon = '📝';
            }
            
            logItem.style.backgroundColor = bgColor;
            logItem.style.color = textColor;
            logItem.innerHTML = `${icon} [${timestamp}] ${message}`;
            
            logContainer.appendChild(logItem);
            logContainer.scrollTop = logContainer.scrollHeight;
        }

        function displayPlanningResult(data) {
            if (!data.success || !data.plan) {
                alert('创建计划失败: ' + (data.error_message || '未知错误'));
                return;
            }

            const plan = data.plan;
            currentPlanId = plan.id;

            // 显示计划详情卡片
            document.getElementById('planningDetailCard').style.display = 'block';
            
            // 填充基本信息
            document.getElementById('planName').textContent = plan.name;
            document.getElementById('planStrategy').textContent = plan.strategy;
            document.getElementById('planDescription').textContent = plan.description;
            
            // 计算统计信息
            const totalTasks = plan.tasks.length;
            const estimatedHours = Math.round(plan.tasks.reduce((sum, task) => sum + task.estimated_duration, 0) / 3600);
            const progress = Math.round(plan.progress * 100);
            
            document.getElementById('totalTasks').textContent = totalTasks;
            document.getElementById('estimatedHours').textContent = estimatedHours + 'h';
            document.getElementById('planProgress').textContent = progress + '%';
            document.getElementById('planStatus').textContent = getStatusText(plan.status);
            
            // 显示任务列表
            displayTasksList(plan.tasks);
            
            // 显示执行按钮
            document.getElementById('executePlanBtn').style.display = 'inline-block';
            document.getElementById('executePlanStreamBtn').style.display = 'inline-block';
            document.getElementById('deletePlanBtn').style.display = 'inline-block';
            
            // 滚动到结果
            document.getElementById('planningDetailCard').scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        function displayTasksList(tasks) {
            const container = document.getElementById('tasksList');
            container.innerHTML = '';
            
            tasks.forEach((task, index) => {
                const taskItem = document.createElement('div');
                taskItem.style.cssText = 'background: white; padding: 16px; border-radius: 8px; margin-bottom: 12px; border-left: 4px solid #007bff;';
                
                const statusColor = getTaskStatusColor(task.status);
                const priorityText = getPriorityText(task.priority);
                const durationText = Math.round(task.estimated_duration / 60) + '分钟';
                
                taskItem.innerHTML = `
                    <div style="display: flex; justify-content: between; align-items: flex-start; margin-bottom: 8px;">
                        <div style="flex: 1;">
                            <div style="font-weight: 600; color: #495057; margin-bottom: 4px;">
                                ${index + 1}. ${task.name}
                            </div>
                            <div style="font-size: 14px; color: #6c757d; margin-bottom: 8px;">
                                ${task.description}
                            </div>
                        </div>
                        <div style="display: flex; gap: 8px; align-items: center;">
                            <span style="background: ${statusColor}; color: white; padding: 4px 8px; border-radius: 4px; font-size: 12px;">
                                ${getStatusText(task.status)}
                            </span>
                            <span style="background: #f8f9fa; color: #495057; padding: 4px 8px; border-radius: 4px; font-size: 12px;">
                                ${priorityText}
                            </span>
                        </div>
                    </div>
                    <div style="display: flex; gap: 16px; font-size: 12px; color: #6c757d;">
                        <span>⏱️ ${durationText}</span>
                        ${task.dependencies.length > 0 ? `<span>🔗 依赖: ${task.dependencies.join(', ')}</span>` : ''}
                        ${task.progress > 0 ? `<span>📊 进度: ${Math.round(task.progress * 100)}%</span>` : ''}
                    </div>
                `;
                
                container.appendChild(taskItem);
            });
        }

        function displayExecutionResult(data) {
            if (!data.success) {
                alert('执行失败: ' + (data.error_message || '未知错误'));
                return;
            }

            // 显示执行结果卡片
            document.getElementById('planningResultCard').style.display = 'block';
            
            // 填充统计信息
            document.getElementById('executionSuccess').textContent = data.success ? '成功' : '失败';
            document.getElementById('completedTasks').textContent = data.completed_tasks || 0;
            document.getElementById('failedTasks').textContent = data.failed_tasks || 0;
            document.getElementById('executionDuration').textContent = formatDuration(data.total_duration);
            
            // 显示执行总结
            const summary = generateExecutionSummary(data);
            document.getElementById('planningFinalResult').innerHTML = marked.parse(summary);
            
            // 滚动到结果
            document.getElementById('planningResultCard').scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        function generateExecutionSummary(data) {
            const totalTasks = data.completed_tasks + data.failed_tasks;
            const successRate = totalTasks > 0 ? Math.round((data.completed_tasks / totalTasks) * 100) : 0;
            
            return `## 执行总结

**执行状态**: ${data.success ? '✅ 成功完成' : '❌ 执行失败'}

**任务统计**:
- 总任务数: ${totalTasks}
- 完成任务: ${data.completed_tasks}
- 失败任务: ${data.failed_tasks}
- 成功率: ${successRate}%

**执行时间**: ${formatDuration(data.total_duration)}

**详细日志**: 共 ${data.execution_log?.length || 0} 条记录

${data.error_message ? `**错误信息**: ${data.error_message}` : ''}

---
*计划执行完成时间: ${new Date().toLocaleString()}*`;
        }

        function getStatusText(status) {
            const statusMap = {
                'pending': '待执行',
                'in_progress': '执行中',
                'completed': '已完成',
                'failed': '失败',
                'blocked': '阻塞',
                'cancelled': '已取消'
            };
            return statusMap[status] || status;
        }

        function getTaskStatusColor(status) {
            const colorMap = {
                'pending': '#6c757d',
                'in_progress': '#007bff',
                'completed': '#28a745',
                'failed': '#dc3545',
                'blocked': '#fd7e14',
                'cancelled': '#6c757d'
            };
            return colorMap[status] || '#6c757d';
        }

        function getPriorityText(priority) {
            const priorityMap = {
                1: '低',
                2: '中',
                3: '高',
                4: '紧急'
            };
            return priorityMap[priority] || '中';
        }

        function formatDuration(seconds) {
            if (!seconds) return '0秒';
            
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = seconds % 60;
            
            if (hours > 0) {
                return `${hours}小时${minutes}分钟`;
            } else if (minutes > 0) {
                return `${minutes}分钟${secs}秒`;
            } else {
                return `${secs}秒`;
            }
        }

        async function showPlanningScenarios() {
            try {
                const response = await fetch('/api/planning/scenarios');
                const data = await response.json();
                
                if (data.success) {
                    displayScenarioList(data.scenarios);
                }
            } catch (error) {
                console.error('获取场景失败:', error);
                alert('获取场景失败: ' + error.message);
            }
        }

        function displayScenarioList(scenarios) {
            const container = document.getElementById('scenarioList');
            container.innerHTML = '';
            
            scenarios.forEach(scenario => {
                const scenarioItem = document.createElement('div');
                scenarioItem.style.cssText = 'background: white; padding: 20px; border-radius: 8px; margin-bottom: 16px; border-left: 4px solid #28a745;';
                
                scenarioItem.innerHTML = `
                    <div style="display: flex; justify-content: between; align-items: flex-start; margin-bottom: 12px;">
                        <div style="flex: 1;">
                            <h4 style="margin: 0 0 8px 0; color: #495057;">${scenario.name}</h4>
                            <p style="margin: 0 0 12px 0; color: #6c757d; font-size: 14px;">${scenario.description}</p>
                        </div>
                        <button class="btn btn-primary" onclick="selectScenario('${scenario.id}')" style="margin-left: 16px;">
                            选择场景
                        </button>
                    </div>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 8px;">
                        ${scenario.features.map(feature => `
                            <div style="background: #f8f9fa; padding: 8px 12px; border-radius: 6px; font-size: 13px; color: #495057;">
                                ${feature}
                            </div>
                        `).join('')}
                    </div>
                `;
                
                container.appendChild(scenarioItem);
            });
            
            document.getElementById('scenarioListCard').style.display = 'block';
            document.getElementById('scenarioListCard').scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        function selectScenario(scenarioId) {
            document.getElementById('planningScenario').value = scenarioId;
            updatePlanningScenarioInfo();
            document.getElementById('scenarioListCard').style.display = 'none';
            document.querySelector('#planningTab .rag-card').scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        function updatePlanningScenarioInfo() {
            const scenario = document.getElementById('planningScenario').value;
            const infoDiv = document.getElementById('planningScenarioInfo');
            
            if (scenario) {
                // 这里可以显示场景的详细信息
                infoDiv.style.display = 'block';
                document.getElementById('planningScenarioDescription').textContent = '已选择预定义场景，将使用模板任务';
                document.getElementById('planningScenarioFeatures').innerHTML = '<div style="color: #28a745;">✅ 使用预定义任务模板</div>';
            } else {
                infoDiv.style.display = 'none';
            }
        }

        function setQuickPlanning(goal) {
            document.getElementById('planningGoal').value = goal;
            document.getElementById('planningGoal').focus();
        }

        function clearPlanningResult() {
            // 隐藏所有结果卡片
            document.getElementById('planningProgressCard').style.display = 'none';
            document.getElementById('planningDetailCard').style.display = 'none';
            document.getElementById('executionProgressCard').style.display = 'none';
            document.getElementById('executionLogCard').style.display = 'none';
            document.getElementById('planningResultCard').style.display = 'none';
            document.getElementById('scenarioListCard').style.display = 'none';
            document.getElementById('allPlansCard').style.display = 'none';
            
            // 清空输入
            document.getElementById('planningGoal').value = '';
            document.getElementById('planningScenario').value = '';
            document.getElementById('autoExecute').checked = false;
            document.getElementById('streamExecution').checked = false;
            
            // 重置当前计划ID
            currentPlanId = null;
            
            // 滚动到顶部
            document.querySelector('#planningTab .rag-card').scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        function copyPlanResult() {
            if (!currentPlanId) return;
            
            const planName = document.getElementById('planName').textContent;
            const planDescription = document.getElementById('planDescription').textContent;
            const totalTasks = document.getElementById('totalTasks').textContent;
            
            const text = `计划名称: ${planName}\n描述: ${planDescription}\n任务数: ${totalTasks}`;
            
            navigator.clipboard.writeText(text).then(() => {
                alert('计划信息已复制到剪贴板');
            }).catch(err => {
                console.error('复制失败:', err);
            });
        }

        function downloadPlanResult() {
            if (!currentPlanId) return;
            
            const planName = document.getElementById('planName').textContent;
            const content = document.getElementById('tasksList').textContent;
            
            const blob = new Blob([content], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `${planName}_计划.txt`;
            a.click();
            URL.revokeObjectURL(url);
        }

        async function deletePlan() {
            if (!currentPlanId) return;
            
            if (!confirm('确定要删除这个计划吗？')) return;
            
            try {
                const response = await fetch(`/api/planning/plan/${currentPlanId}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    alert('计划已删除');
                    clearPlanningResult();
                } else {
                    throw new Error('删除失败');
                }
            } catch (error) {
                console.error('删除计划失败:', error);
                alert('删除计划失败: ' + error.message);
            }
        }

        async function showAllPlans() {
            try {
                const response = await fetch('/api/planning/plans');
                const data = await response.json();
                
                if (data.success) {
                    displayAllPlansList(data.plans);
                }
            } catch (error) {
                console.error('获取计划列表失败:', error);
                alert('获取计划列表失败: ' + error.message);
            }
        }

        function displayAllPlansList(plans) {
            const container = document.getElementById('allPlansList');
            container.innerHTML = '';
            
            if (plans.length === 0) {
                container.innerHTML = '<div style="text-align: center; color: #6c757d; padding: 40px;">暂无计划</div>';
            } else {
                plans.forEach(plan => {
                    const planItem = document.createElement('div');
                    planItem.style.cssText = 'background: white; padding: 16px; border-radius: 8px; margin-bottom: 12px; border-left: 4px solid #007bff;';
                    
                    const progress = Math.round(plan.progress * 100);
                    const estimatedHours = Math.round(plan.tasks.reduce((sum, task) => sum + task.estimated_duration, 0) / 3600);
                    
                    planItem.innerHTML = `
                        <div style="display: flex; justify-content: between; align-items: flex-start;">
                            <div style="flex: 1;">
                                <h5 style="margin: 0 0 8px 0; color: #495057;">${plan.name}</h5>
                                <p style="margin: 0 0 8px 0; color: #6c757d; font-size: 14px;">${plan.description}</p>
                                <div style="display: flex; gap: 16px; font-size: 12px; color: #6c757d;">
                                    <span>📋 ${plan.tasks.length} 个任务</span>
                                    <span>⏱️ ${estimatedHours}小时</span>
                                    <span>📊 ${progress}%</span>
                                    <span>📅 ${new Date(plan.created_at).toLocaleDateString()}</span>
                                </div>
                            </div>
                            <div style="display: flex; gap: 8px; margin-left: 16px;">
                                <button class="btn btn-sm btn-secondary" onclick="loadPlan('${plan.id}')">
                                    查看
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="deletePlanFromList('${plan.id}')">
                                    删除
                                </button>
                            </div>
                        </div>
                    `;
                    
                    container.appendChild(planItem);
                });
            }
            
            document.getElementById('allPlansCard').style.display = 'block';
            document.getElementById('allPlansCard').scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        async function loadPlan(planId) {
            try {
                const response = await fetch(`/api/planning/plan/${planId}`);
                const data = await response.json();
                
                if (data.success) {
                    displayPlanningResult({ success: true, plan: data.plan });
                    document.getElementById('allPlansCard').style.display = 'none';
                }
            } catch (error) {
                console.error('加载计划失败:', error);
                alert('加载计划失败: ' + error.message);
            }
        }

        async function deletePlanFromList(planId) {
            if (!confirm('确定要删除这个计划吗？')) return;
            
            try {
                const response = await fetch(`/api/planning/plan/${planId}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    showAllPlans(); // 重新加载列表
                } else {
                    throw new Error('删除失败');
                }
            } catch (error) {
                console.error('删除计划失败:', error);
                alert('删除计划失败: ' + error.message);
            }
        }

        function copyPlanningResult() {
            const result = document.getElementById('planningFinalResult').textContent;
            navigator.clipboard.writeText(result).then(() => {
                alert('执行结果已复制到剪贴板');
            }).catch(err => {
                console.error('复制失败:', err);
            });
        }

        function downloadPlanningResult() {
            const result = document.getElementById('planningFinalResult').textContent;
            const blob = new Blob([result], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'planning_result.txt';
            a.click();
            URL.revokeObjectURL(url);
        }

        function showPlanningLog() {
            const logCard = document.getElementById('executionLogCard');
            if (logCard.style.display === 'none') {
                logCard.style.display = 'block';
                logCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
            } else {
                logCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        }

        // ========== Multi-Agent Collaboration Functions ==========

        let collaborationTeamsData = null;
        let collaborationModesData = null;
        let currentCollaborationResult = null;

        // 加载团队和模式信息
        async function loadCollaborationData() {
            try {
                const [teamsResponse, modesResponse] = await Promise.all([
                    fetch('/api/multi-agent/teams'),
                    fetch('/api/multi-agent/modes')
                ]);
                
                const teamsData = await teamsResponse.json();
                const modesData = await modesResponse.json();
                
                if (teamsData.success) {
                    collaborationTeamsData = teamsData.teams;
                }
                
                if (modesData.success) {
                    collaborationModesData = modesData.modes;
                }
            } catch (error) {
                console.error('加载协作数据失败:', error);
            }
        }

        // 更新团队信息
        function updateTeamInfo() {
            const teamType = document.getElementById('collaborationTeam').value;
            const teamInfoCard = document.getElementById('teamInfoCard');
            
            if (!teamType || !collaborationTeamsData) {
                teamInfoCard.style.display = 'none';
                return;
            }
            
            const team = collaborationTeamsData[teamType];
            if (!team) return;
            
            document.getElementById('teamDescription').textContent = team.description;
            
            // 显示 Agents
            let agentsHTML = '<div style="margin-bottom: 8px; font-weight: 600; color: #495057;">团队成员：</div><div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 8px;">';
            team.agents.forEach(agent => {
                agentsHTML += `
                    <div style="background: white; padding: 8px; border-radius: 6px; border: 1px solid #dee2e6;">
                        <div style="font-weight: 600; font-size: 13px; color: #495057; margin-bottom: 4px;">${agent.name}</div>
                        <div style="font-size: 11px; color: #6c757d;">${agent.expertise.join(', ')}</div>
                    </div>
                `;
            });
            agentsHTML += '</div>';
            document.getElementById('teamAgents').innerHTML = agentsHTML;
            
            // 显示使用场景
            let useCasesHTML = '<div style="margin-bottom: 8px; font-weight: 600; color: #495057;">适用场景：</div><div style="display: flex; flex-wrap: wrap; gap: 8px;">';
            team.use_cases.forEach(useCase => {
                useCasesHTML += `<span style="background: #e7f3ff; color: #004085; padding: 4px 12px; border-radius: 12px; font-size: 13px;">${useCase}</span>`;
            });
            useCasesHTML += '</div>';
            document.getElementById('teamUseCases').innerHTML = useCasesHTML;
            
            teamInfoCard.style.display = 'block';
        }

        // 设置快速协作任务
        function setQuickCollaboration(task, teamType) {
            document.getElementById('collaborationTask').value = task;
            document.getElementById('collaborationTeam').value = teamType;
            updateTeamInfo();
        }

        // 开始协作
        async function startCollaboration() {
            const task = document.getElementById('collaborationTask').value.trim();
            const teamType = document.getElementById('collaborationTeam').value;
            const mode = document.getElementById('collaborationMode').value;
            
            if (!task) {
                alert('请输入任务描述');
                return;
            }
            
            if (!teamType) {
                alert('请选择协作团队');
                return;
            }
            
            const startBtn = document.getElementById('collaborationStartBtn');
            startBtn.disabled = true;
            startBtn.textContent = '协作中...';
            
            // 显示进度卡片
            document.getElementById('collaborationProgressCard').style.display = 'block';
            document.getElementById('collaborationStatus').textContent = '正在初始化协作...';
            
            // 隐藏之前的结果
            document.getElementById('agentContributionsCard').style.display = 'none';
            document.getElementById('collaborationMessagesCard').style.display = 'none';
            document.getElementById('collaborationResultCard').style.display = 'none';
            
            try {
                // 使用流式 API
                const response = await fetch('/api/multi-agent/collaborate/stream', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        input_text: task,
                        team_type: teamType,
                        mode: mode
                    })
                });
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                
                while (true) {
                    const {value, done} = await reader.read();
                    if (done) break;
                    
                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = JSON.parse(line.slice(6));
                            handleCollaborationEvent(data);
                        }
                    }
                }
                
            } catch (error) {
                console.error('协作失败:', error);
                alert('协作失败: ' + error.message);
                document.getElementById('collaborationStatus').textContent = '协作失败: ' + error.message;
            } finally {
                startBtn.disabled = false;
                startBtn.textContent = '🚀 开始协作';
            }
        }

        // 处理协作事件
        function handleCollaborationEvent(data) {
            const statusDiv = document.getElementById('collaborationStatus');
            
            switch (data.type) {
                case 'start':
                    statusDiv.textContent = data.message;
                    break;
                    
                case 'team_info':
                    const teamInfoHTML = `
                        <div style="font-weight: 600; margin-bottom: 8px;">团队: ${data.team_name} (${data.agent_count} 个 Agents)</div>
                        <div style="font-size: 13px; color: #6c757d;">模式: ${data.mode}</div>
                    `;
                    document.getElementById('collaborationTeamInfo').innerHTML = teamInfoHTML;
                    statusDiv.textContent = '团队已组建，开始协作...';
                    break;
                    
                case 'complete':
                    currentCollaborationResult = data;
                    displayCollaborationResult(data);
                    statusDiv.textContent = '协作已完成！';
                    break;
                    
                case 'error':
                    statusDiv.textContent = data.message;
                    statusDiv.style.color = '#dc3545';
                    break;
            }
        }

        // 显示协作结果
        function displayCollaborationResult(data) {
            if (!data.success) {
                alert('协作失败: ' + data.error_message);
                return;
            }
            
            // 显示统计信息
            document.getElementById('collaborationSuccess').textContent = data.success ? '✅ 成功' : '❌ 失败';
            document.getElementById('agentCount').textContent = Object.keys(data.agent_contributions).length;
            document.getElementById('messageCount').textContent = data.messages.length;
            document.getElementById('collaborationTime').textContent = data.execution_time.toFixed(1) + 's';
            
            // 显示最终输出
            const outputDiv = document.getElementById('collaborationFinalOutput');
            outputDiv.innerHTML = DOMPurify.sanitize(marked.parse(data.final_output));
            
            // 显示 Agent 贡献
            displayAgentContributions(data.agent_contributions);
            
            // 显示消息记录
            displayCollaborationMessages(data.messages);
            
            // 显示结果卡片
            document.getElementById('collaborationResultCard').style.display = 'block';
            document.getElementById('collaborationResultCard').scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        // 显示 Agent 贡献
        function displayAgentContributions(contributions) {
            const container = document.getElementById('agentContributionsList');
            container.innerHTML = '';
            
            for (const [agentName, contribution] of Object.entries(contributions)) {
                const contributionDiv = document.createElement('div');
                contributionDiv.style.cssText = 'background: white; padding: 16px; border-radius: 8px; margin-bottom: 12px; border-left: 4px solid #667eea;';
                
                const roleIcons = {
                    'coordinator': '📋',
                    'specialist': '🎯',
                    'reviewer': '🔍',
                    'executor': '⚙️',
                    'advisor': '💡'
                };
                
                const roleIcon = roleIcons[contribution.role] || '🤖';
                
                contributionDiv.innerHTML = `
                    <div style="display: flex; align-items: center; margin-bottom: 12px;">
                        <span style="font-size: 24px; margin-right: 12px;">${roleIcon}</span>
                        <div>
                            <h5 style="margin: 0; color: #495057;">${agentName}</h5>
                            <div style="font-size: 12px; color: #6c757d;">${contribution.role}</div>
                        </div>
                    </div>
                    <div class="markdown-content" style="font-size: 14px;">
                        ${DOMPurify.sanitize(marked.parse(contribution.response))}
                    </div>
                `;
                
                container.appendChild(contributionDiv);
            }
            
            document.getElementById('agentContributionsCard').style.display = 'block';
        }

        // 显示消息记录
        function displayCollaborationMessages(messages) {
            const container = document.getElementById('messagesList');
            container.innerHTML = '';
            
            messages.forEach(message => {
                const messageDiv = document.createElement('div');
                messageDiv.style.cssText = 'background: #f8f9fa; padding: 12px; border-radius: 6px; margin-bottom: 8px; font-size: 13px;';
                
                const typeIcons = {
                    'task': '📋',
                    'response': '💬',
                    'feedback': '💡',
                    'query': '❓'
                };
                
                const icon = typeIcons[message.type] || '💬';
                
                messageDiv.innerHTML = `
                    <div style="display: flex; justify-content: space-between; margin-bottom: 6px;">
                        <span style="font-weight: 600; color: #495057;">${icon} ${message.sender} → ${message.receiver}</span>
                        <span style="color: #6c757d; font-size: 11px;">${new Date(message.timestamp * 1000).toLocaleTimeString()}</span>
                    </div>
                    <div style="color: #6c757d;">${message.content.substring(0, 200)}${message.content.length > 200 ? '...' : ''}</div>
                `;
                
                container.appendChild(messageDiv);
            });
            
            document.getElementById('collaborationMessagesCard').style.display = 'block';
        }

        // 清除协作结果
        function clearCollaborationResult() {
            document.getElementById('collaborationProgressCard').style.display = 'none';
            document.getElementById('agentContributionsCard').style.display = 'none';
            document.getElementById('collaborationMessagesCard').style.display = 'none';
            document.getElementById('collaborationResultCard').style.display = 'none';
            currentCollaborationResult = null;
        }

        // 复制协作结果
        function copyCollaborationResult() {
            if (!currentCollaborationResult) return;
            
            const result = currentCollaborationResult.final_output;
            navigator.clipboard.writeText(result).then(() => {
                alert('协作结果已复制到剪贴板');
            }).catch(err => {
                console.error('复制失败:', err);
            });
        }

        // 下载协作结果
        function downloadCollaborationResult() {
            if (!currentCollaborationResult) return;
            
            const task = document.getElementById('collaborationTask').value.trim();
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
            const filename = `collaboration_${timestamp}.md`;
            
            let content = `# 多智能体协作结果\n\n`;
            content += `**任务**: ${task}\n\n`;
            content += `**团队**: ${document.getElementById('collaborationTeam').selectedOptions[0].text}\n`;
            content += `**模式**: ${document.getElementById('collaborationMode').selectedOptions[0].text}\n`;
            content += `**参与 Agent 数**: ${Object.keys(currentCollaborationResult.agent_contributions).length}\n`;
            content += `**执行时间**: ${currentCollaborationResult.execution_time.toFixed(1)}s\n\n`;
            content += `---\n\n`;
            content += `## 最终输出\n\n${currentCollaborationResult.final_output}\n\n`;
            content += `---\n\n`;
            content += `## Agent 贡献\n\n`;
            
            for (const [agentName, contribution] of Object.entries(currentCollaborationResult.agent_contributions)) {
                content += `### ${agentName} (${contribution.role})\n\n`;
                content += `${contribution.response}\n\n`;
            }
            
            const blob = new Blob([content], { type: 'text/markdown' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            a.click();
            URL.revokeObjectURL(url);
        }

        // 显示团队详情
        async function showTeamDetails() {
            if (!collaborationTeamsData) {
                await loadCollaborationData();
            }
            
            let html = '<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 16px;">';
            
            for (const [teamId, team] of Object.entries(collaborationTeamsData)) {
                html += `
                    <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid #dee2e6;">
                        <h4 style="margin: 0 0 12px 0; color: #495057;">${team.name}</h4>
                        <p style="margin: 0 0 12px 0; color: #6c757d; font-size: 13px;">${team.description}</p>
                        <div style="font-size: 12px; color: #6c757d;">
                            <div style="font-weight: 600; margin-bottom: 6px;">成员 (${team.agents.length}):</div>
                            ${team.agents.map(a => `<div>• ${a.name}</div>`).join('')}
                        </div>
                    </div>
                `;
            }
            
            html += '</div>';
            
            alert('团队详情已在控制台输出');
            console.log('协作团队:', collaborationTeamsData);
        }

        // 显示模式详情
        async function showModeDetails() {
            if (!collaborationModesData) {
                await loadCollaborationData();
            }
            
            let html = '<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 16px;">';
            
            for (const [modeId, mode] of Object.entries(collaborationModesData)) {
                html += `
                    <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid #dee2e6;">
                        <h4 style="margin: 0 0 8px 0; color: #495057;">${mode.icon} ${mode.name}</h4>
                        <p style="margin: 0 0 8px 0; color: #6c757d; font-size: 13px;">${mode.description}</p>
                        <div style="font-size: 12px; color: #6c757d; font-style: italic;">${mode.use_case}</div>
                    </div>
                `;
            }
            
            html += '</div>';
            
            alert('模式详情已在控制台输出');
            console.log('协作模式:', collaborationModesData);
        }

        // 显示协作详情
        function showCollaborationDetails() {
            if (!currentCollaborationResult) return;
            
            console.log('完整协作结果:', currentCollaborationResult);
            alert('完整协作结果已在控制台输出，可以按 F12 查看');
        }

        // ==================== Memory Management 相关函数 ====================
        const MEMORY_SESSION_ID = 'default';

        // 存储记忆
        async function storeMemory() {
            const content = document.getElementById('memoryContent').value.trim();
            if (!content) {
                alert('请输入记忆内容');
                return;
            }
            
            const memoryType = document.getElementById('memoryType').value;
            const importance = parseInt(document.getElementById('memoryImportance').value);
            const tagsStr = document.getElementById('memoryTags').value;
            const tags = tagsStr ? tagsStr.split(',').map(t => t.trim()) : [];
            
            try {
                const response = await fetch('/api/memory/store', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        content: content,
                        memory_type: memoryType,
                        importance: importance,
                        tags: tags,
                        session_id: MEMORY_SESSION_ID
                    })
                });
                
                const data = await response.json();
                if (data.success) {
                    alert('✅ 记忆已存储！');
                    document.getElementById('memoryContent').value = '';
                    document.getElementById('memoryTags').value = '';
                    loadMemoryStats();
                }
            } catch (error) {
                console.error('存储记忆失败:', error);
                alert('存储记忆失败，请重试');
            }
        }

        // 检索记忆
        async function retrieveMemories() {
            const query = document.getElementById('memoryQuery').value.trim();
            if (!query) {
                alert('请输入查询内容');
                return;
            }
            
            const memoryTypes = [];
            if (document.getElementById('filterSemantic').checked) memoryTypes.push('semantic');
            if (document.getElementById('filterEpisodic').checked) memoryTypes.push('episodic');
            if (document.getElementById('filterLongTerm').checked) memoryTypes.push('long_term');
            
            try {
                const response = await fetch('/api/memory/retrieve', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        query: query,
                        memory_types: memoryTypes.length > 0 ? memoryTypes : null,
                        top_k: 10,
                        session_id: MEMORY_SESSION_ID
                    })
                });
                
                const data = await response.json();
                displayMemoryResults(data.results);
            } catch (error) {
                console.error('检索记忆失败:', error);
                alert('检索记忆失败，请重试');
            }
        }

        // 显示检索结果
        function displayMemoryResults(results) {
            const container = document.getElementById('memoryResults');
            if (!results || results.length === 0) {
                container.innerHTML = '<p style="color: #999; text-align: center; padding: 40px 20px;">未找到相关记忆</p>';
                return;
            }
            
            container.innerHTML = results.map(result => {
                const memoryTypeIcons = {
                    'semantic': '📚',
                    'episodic': '📖',
                    'long_term': '💾',
                    'short_term': '⚡',
                    'working': '🔧',
                    'procedural': '⚙️'
                };
                const icon = memoryTypeIcons[result.memory.memory_type] || '💭';
                
                return `
                    <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 10px; border-left: 3px solid #667eea;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 8px; font-size: 12px; color: #666;">
                            <span>${icon} ${result.memory.memory_type}</span>
                            <span>相关性: ${(result.relevance_score * 100).toFixed(0)}%</span>
                        </div>
                        <div style="font-size: 14px; color: #333; margin-bottom: 8px;">${result.memory.content}</div>
                        <div style="display: flex; flex-wrap: wrap; gap: 5px;">
                            ${result.memory.tags.map(tag => `<span style="background: #667eea; color: white; padding: 3px 8px; border-radius: 12px; font-size: 11px;">${tag}</span>`).join('')}
                        </div>
                    </div>
                `;
            }).join('');
        }

        // 加载记忆统计
        async function loadMemoryStats() {
            try {
                const response = await fetch(`/api/memory/statistics/${MEMORY_SESSION_ID}`);
                const data = await response.json();
                
                if (data.success) {
                    const stats = data.statistics;
                    const memoryTypeIcons = {
                        'semantic': '📚',
                        'episodic': '📖',
                        'long_term': '💾',
                        'short_term': '⚡',
                        'working': '🔧',
                        'procedural': '⚙️'
                    };
                    
                    let html = `<p><strong>📊 总记忆数:</strong> ${stats.total_memories}</p>`;
                    
                    if (Object.keys(stats.by_type).length > 0) {
                        html += `<p><strong>📦 按类型分布:</strong></p>`;
                        for (const [type, count] of Object.entries(stats.by_type)) {
                            const icon = memoryTypeIcons[type] || '💭';
                            html += `<p style="margin-left:15px">${icon} ${type}: ${count}</p>`;
                        }
                    }
                    
                    html += `<p><strong>💾 存储大小:</strong> ${stats.storage_size_kb} KB</p>`;
                    
                    document.getElementById('memoryStats').innerHTML = html;
                }
            } catch (error) {
                console.error('加载统计失败:', error);
                document.getElementById('memoryStats').innerHTML = '<p style="color: #dc3545;">加载失败，请重试</p>';
            }
        }

        // 基于记忆的对话
        async function sendMemoryChat() {
            const input = document.getElementById('memoryChatInput');
            const userInput = input.value.trim();
            if (!userInput) return;
            
            // 添加用户消息
            addMemoryMessage('user', userInput);
            input.value = '';
            
            try {
                const response = await fetch('/api/memory/chat', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        user_input: userInput,
                        session_id: MEMORY_SESSION_ID
                    })
                });
                
                const data = await response.json();
                if (data.success) {
                    addMemoryMessage('assistant', data.response);
                }
            } catch (error) {
                console.error('对话失败:', error);
                addMemoryMessage('assistant', '抱歉，对话失败，请重试');
            }
        }

        // 添加消息到对话区域
        function addMemoryMessage(role, content) {
            const container = document.getElementById('memoryMessages');
            const messageDiv = document.createElement('div');
            messageDiv.style.cssText = `
                margin-bottom: 12px;
                padding: 10px 15px;
                border-radius: 8px;
                ${role === 'user' ? 'background: #667eea; color: white; margin-left: 40px; text-align: right;' : 'background: white; margin-right: 40px;'}
            `;
            messageDiv.textContent = content;
            container.appendChild(messageDiv);
            container.scrollTop = container.scrollHeight;
        }

        // 页面加载时初始化
        (function() {
            const originalInit = window.onload;
            window.onload = function() {
                if (originalInit) originalInit();
                loadReflectionScenarios();
                loadCollaborationData();  // 加载协作数据
                
                // 初始化Memory标签时加载统计
                const memoryTab = document.querySelector('[onclick*="memory"]');
                if (memoryTab) {
                    memoryTab.addEventListener('click', function() {
                        setTimeout(loadMemoryStats, 100);
                    });
                }
            };
        })();
    </script>
</body>
</html>
